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")
}
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.
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With