How to extract a Zip file with PowerShell?
It is possible to extract the zip file using Powershell and there are multiple ways to achieve this. We will explore each method.
Methods to extract Zip Files
- Expand-Archive cmdlet
- ZipFile.ExtractToDirectory
- 7Zip module
There are other methods as well but we will cover the most commonly used one.
1. Expand-Archive cmdlet
The expand-Archive cmdlet is used to extract the zip file which is part of Microsoft.PowerShell.Archive module. To know more about the Expand-Archive command, refer to the link below.
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.archive/expand-archive
We need to extract the C:\Temp\TestFolder.zip to the C:\path. You can also use the UNC path as a source or destination.
Expand-Archive -Path C:\Temp\TestFolder.zip -DestinationPath C:\ -Force -Verbose
-Path is the source file path, -DestinationPath is for the destination folder path, and -Force is to overwrite the destination files if already exist.
2. ZipFile.ExtractToDirectory Method
The ZipFile.ExtractToDirectory method is available with the .Net class. It is also supported in lower versions of .Net (of course limited functions).
In case your windows operating system running PowerShell 5.1 below (for a higher version it always works) then use this method.
https://learn.microsoft.com/en-us/dotnet/api/system.io.compression.zipfile.extracttodirectory
Not every Operating system has loaded the zip file assembly by default. For that, you need to load the assembly and run the command to unzip the file.
Add-Type -AssemblyName System.IO.Compression.FileSystem
[System.IO.Compression.ZipFile]::ExtractToDirectory("C:\Temp\TestFolder.zip","C:\")
The first line will load the assembly and the second command will unzip the TestFolder.zip to the C drive.
3. 7Zip command line
You can also download the 7Zip Powershell module from the PowerShell gallery.
https://www.powershellgallery.com/packages/7Zip4Powershell/
To download and Install the 7Zip module from the PowerShell gallery, use the below command.
Install-Module -Name 7Zip4Powershell
After installing this module, check what commands are available,
We can use Expand-7Zip to extract the files.
Expand-7Zip -ArchiveFileName C:\Temp\TestFolder.zip -TargetPath C:\