Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unzip a Zip File with Powershell Version 2.0?

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")
}
like image 276
Raphael Avatar asked Jun 14 '16 13:06

Raphael


People also ask

How do I unzip a ZIP file in Windows Terminal?

To unzip a single file or folder, open the zipped folder, then drag the file or folder from the zipped folder to a new location. To unzip all the contents of the zipped folder, press and hold (or right-click) the folder, select Extract All, and then follow the instructions.


2 Answers

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/

like image 69
FoxDeploy Avatar answered Oct 30 '22 12:10

FoxDeploy


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.

like image 33
Ansgar Wiechers Avatar answered Oct 30 '22 10:10

Ansgar Wiechers