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

时间:2016-06-14 13:52:28

标签: powershell powershell-v2.0 powershell-v4.0

这适用于PowerShell 4.0或更高版本。但是在PowerShell 2.0版本中,Add-Type是不可能的(类型不存在)。

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

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

2 个答案:

答案 0 :(得分:8)

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)
}
}

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

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

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

答案 1 :(得分:7)

PowerShell版本只是一个症状。这不是问题的真正原因。处理zip存档的相关类已添加到System.IO.Compression命名空间,其中包含.NET Framework 4.5(PowerShell v4的先决条件),但在earlier versions中不可用。安装.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配置更改为always use the latest 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,开箱即用的替代方案是Shell.Application COM对象,如@FoxDeploy所示。但要注意,CopyHere()方法异步运行,即它立即返回,而不等待实际的复制操作完成。如果要从脚本运行它,则需要添加某种延迟,因为当脚本终止时会自动销毁Shell.Application对象,从而中止未完成的复制操作。

相关问题