How to unzip a Zip File with Powershell Version 2.

2019-01-28 01:36发布

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

2条回答
beautiful°
2楼-- · 2019-01-28 02:21

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.

查看更多
看我几分像从前
3楼-- · 2019-01-28 02:23
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/

查看更多
登录 后发表回答