How to unzip a Zip File with Powershell Version 2.0?

谁都会走 提交于 2019-11-28 07:41:15

问题


This works for me with PowerShell version 4.0 or higher. But at PowerShell version 2.0 the Add-Type isn't possible (type doesn't exist).

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

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

回答1:


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

This leverages Windows's built in zip file support, via the Shell.Application object. To use this, run the following.

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

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




回答2:


The PowerShell version is just a symptom. It's not the actual cause of the issue. The relevant classes for handling zip archives were added to the System.IO.Compression namespace with .NET Framework 4.5 (a prerequisite for PowerShell v4) and are not available in earlier versions. Install version 4.5 of the .NET Framework and you'll be able to use the IO.Compression.ZipFile class in PowerShell v2 as well.

However, in PowerShell v2

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

will throw an error that it cannot find the assembly even if you installed .NET Framework 4.5, so you'll need to replace the line with

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

and change the .Net Framework configuration to always use the latest CLR (otherwise PowerShell v2 would use .Net Framework 2.0 instead of 4.5):

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

An alternative that works out of the box even without .NET Framework 4.5 is the Shell.Application COM object, as suggested by @FoxDeploy. Beware, though, that the CopyHere() method runs asynchronously, i.e. it returns immediately without waiting for the actual copy operation to complete. If you want to run it from a script you need to add some sort of delay, because the Shell.Application object is automatically destroyed when the script terminates, thus aborting unfinished copy operations.



来源:https://stackoverflow.com/questions/37814037/how-to-unzip-a-zip-file-with-powershell-version-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!