如何使用Powershell版本2.0解压缩Zip文件?

8

这对我来说在PowerShell 4.0或更高版本中有效。但是在PowerShell 2.0版本中,Add-Type不可用(类型不存在)。

function unzip {
    Add-Type -Assembly “system.io.compression.filesystem”

    [io.compression.zipfile]::ExtractToDirectory("SOURCEPATH\ZIPNAME", "DESTINATIONPATH")
}

1
我在http://stackoverflow.com/questions/44030884/creating-zip-files-using-powershell/44031912#44031912中回答了这个问题。 - randiel
2个回答

13
function Expand-ZIPFile($file, $destination)
{
   $shell = new-object -com shell.application
   $zip = $shell.NameSpace($file)
   foreach($item in $zip.items())
   {
      $shell.Namespace($destination).copyhere($item)
   }
}

这利用了Windows内置的zip文件支持,通过Shell.Application对象实现。要使用它,请运行以下命令。

>Expand-ZipFile .\Myzip.zip -destination c:\temp\files

来源: http://www.howtogeek.com/tips/how-to-extract-zip-files-using-powershell/


9
PowerShell版本只是症状,并非实际问题的根本原因。有关处理zip存档的相关类被添加到了System.IO.Compression命名空间中,随着.NET Framework 4.5的推出(PowerShell v4的前提条件),并且在早期版本中不可用。安装.NET Framework 4.5版本后,您也将能够在PowerShell v2中使用IO.Compression.ZipFile类。

然而,在PowerShell v2中

Add-Type -Assembly "System.IO.Compression.Filesystem"

如果您安装了.NET Framework 4.5,但仍然无法找到程序集,则会抛出错误,因此您需要将该行替换为

[Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.Filesystem")

并将 .Net Framework 配置更改为 始终使用最新的CLR (否则,PowerShell v2 将使用 .Net Framework 2.0 而不是 4.5):

reg add HKLM\SOFTWARE\Microsoft\.NETFramework /v OnlyUseLatestCLR /t REG_DWORD /d 1

一个即插即用的替代方案,即使没有.NET Framework 4.5也可以工作,就是由@FoxDeploy建议的Shell.Application COM对象。请注意,CopyHere()方法运行异步,即它立即返回而不等待实际复制操作完成。如果您想从脚本中运行它,您需要添加一些延迟,因为Shell.Application对象在脚本终止时自动销毁,从而中止未完成的复制操作。

以下是错误信息: PS C:\Users\test> [Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.Filesystem")PS C:\Users\test> [io.compression.zipfile]::ExtractToDirectory("C:\WIN_AGENT.zip", "C:\test") 无法找到类型 [io.compression.zipfile]:请确保包含此类型的程序集已加载。 位于第 1 行字符 25
  • [io.compression.zipfile] <<<< ::ExtractToDirectory("C:\WIN_AGENT.zip", "C:\test")
    • CategoryInfo : InvalidOperation: (io.compression.zipfile:String) [], RuntimeException
    • FullyQualifiedErrorId : TypeNotFound
- Raphael
很遗憾,我无法更改实际的.NET Framework版本。 所使用的.NET Framework版本为2.0。 - Raphael
这个答案是不正确的。首先,Add-Type在PowerShell V2中是可用的。其次,[Reflection.Assembly] :: LoadWithPartialName(“System.IO.Compression.Filesystem”)将无法在PowerShell V2中工作,因为它使用.NET 2。 - richb
@richb,你说得没错,Add-Type在PowerShell v2中是可用的。但是,如果你运行Add-Type -Assembly 'System.IO.Compression.Filesystem',你会发现它抱怨找不到程序集。此外,[Reflection.Assembly]::LoadWithPartialName()不能在PowerShell v2中使用是不正确的。你只需要让它使用最新的CLR版本即可。 - Ansgar Wiechers
有趣的Ansgar,我之前不知道这个。对于我的用例来说,它没有用处。我想要一个可以在普通的Windows 7上运行的脚本。如果我要在每台计算机上更改注册表才能使其工作,那么我可能会直接安装PowerShell 5。我还注意到该答案中关于强制PS 2在.NET 4上运行的负面影响的评论。尽管如此,这是一个有趣的技巧,谢谢提供信息。 - richb
如果你想要一个能在普通的Windows 7上运行的脚本,你可能只能使用Shell.Application COM对象,因为据我所知,其他所有东西都需要对系统进行某种修改(如.NET Framework升级、第三方程序如7-zip等)。 - Ansgar Wiechers

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接