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

Rap*_*ael 7 powershell powershell-2.0 powershell-4.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")
}
Run Code Online (Sandbox Code Playgroud)

Fox*_*loy 9

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)
}
}
Run Code Online (Sandbox Code Playgroud)

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

>Expand-ZipFile .\Myzip.zip -destination c:\temp\files
Run Code Online (Sandbox Code Playgroud)

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


Ans*_*ers 8

PowerShell版本只是一个症状.这不是问题的真正原因.System.IO.Compression使用.NET Framework 4.5(PowerShell v4的先决条件)将用于处理zip存档的相关类添加到命名空间中,并且在早期版本中不可用.安装.NET Framework 4.5版,您也可以IO.Compression.ZipFile在PowerShell v2中使用该类.

但是,在PowerShell v2中

Add-Type -Assembly "System.IO.Compression.Filesystem"
Run Code Online (Sandbox Code Playgroud)

即使您安装了.NET Framework 4.5,也会抛出无法找到程序集的错误,因此您需要替换该行

[Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.Filesystem")
Run Code Online (Sandbox Code Playgroud)

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

reg add HKLM\SOFTWARE\Microsoft\.NETFramework /v OnlyUseLatestCLR /t REG_DWORD /d 1
Run Code Online (Sandbox Code Playgroud)

即使没有.NET Framework 4.5,开箱即用的替代方案是Shell.ApplicationCOM对象,正如@FoxDeploy所建议的那样.但要注意,该CopyHere()方法是异步运行的,即它会立即返回,而不必等待实际的复制操作完成.如果要从脚本运行它,则需要添加某种延迟,因为Shell.Application在脚本终止时会自动销毁该对象,从而中止未完成的复制操作.

  • 你真的**读**我在答案中写的内容怎么样? (4认同)