这对我来说在PowerShell 4.0或更高版本中有效。但是在PowerShell 2.0版本中,Add-Type
不可用(类型不存在)。
function unzip {
Add-Type -Assembly “system.io.compression.filesystem”
[io.compression.zipfile]::ExtractToDirectory("SOURCEPATH\ZIPNAME", "DESTINATIONPATH")
}
这对我来说在PowerShell 4.0或更高版本中有效。但是在PowerShell 2.0版本中,Add-Type
不可用(类型不存在)。
function unzip {
Add-Type -Assembly “system.io.compression.filesystem”
[io.compression.zipfile]::ExtractToDirectory("SOURCEPATH\ZIPNAME", "DESTINATIONPATH")
}
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/
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
Shell.Application
COM对象。请注意,CopyHere()
方法运行异步,即它立即返回而不等待实际复制操作完成。如果您想从脚本中运行它,您需要添加一些延迟,因为Shell.Application
对象在脚本终止时自动销毁,从而中止未完成的复制操作。Add-Type
在PowerShell v2中是可用的。但是,如果你运行Add-Type -Assembly 'System.IO.Compression.Filesystem'
,你会发现它抱怨找不到程序集。此外,[Reflection.Assembly]::LoadWithPartialName()
不能在PowerShell v2中使用是不正确的。你只需要让它使用最新的CLR版本即可。 - Ansgar WiechersShell.Application
COM对象,因为据我所知,其他所有东西都需要对系统进行某种修改(如.NET Framework升级、第三方程序如7-zip等)。 - Ansgar Wiechers