PowerShell – Unzip File

Using Expand-Archive Cmdlet

Use the Expand-Achrive cmdlet to unzip a file/folder in PowerShell.

Please note that Expand-Archive cmdlet is available from PowerShell 5 onwards. Print envionment variable $PSVersionTable.PSVersion to check version of your PowerShell.

We used the Expand-Achrive cmdlet to unzip a folder from the given location and save the unzipped folder in the specified destination. Note that this cmdlet will create an ExtractedFolderA folder if it does not exist in the given destination.

An archive file allows many files to be packaged and compressed (optionally) into one zipped file for more accessible storage and distribution.

What if we have already unzipped the file in the specified destination but want to unzip it again for some reason? This is where we can use the -Force parameter, which is used to overwrite the files/folders in the destination path if the same files/folders already exist.

Note that the -Force parameter overwrites without the user’s confirmation, so be aware while using it, as given below.

We can use the following command to save the extracted data in the current directory, which is represented with a dot (.).

Remember, we can use the -LiteralPath parameter name instead of -Path if we have wildcard characters in the file name; see the following example.

Using System.IO.Compression.ZipFile Namespace

To unzip a file/folder in PowerShell:

  • Add a reference to the System.IO.Compression.Filesystem assembly in the script.
  • Use the System.IO.Compression.ZipFile namespace to unzip files/folders in the destination path.

In the above code, we added the assembly using Add-Type; it is required if the ZipFile class is unavailable in PowerShell. Next, we used the .Net namespace System.IO.Compression class ZipFile to unzip files/folders or extract data from the specified compressed file.

The ZipFile class is introduced in .Net Framework 4.5 to manage archive files; it provides static methods to create, extract, and open archive files. Here, we used the ExtractToDirectory() method to extract a compressed file from the source to the destination path.

To read the archived files, use OpenRead(). We can also use the Select-Object cmdlet to list all the extracted items. See the following example.

Using 7Zip Module

Use the 7Zip Module to unzip files/folders in PowerShell.

It is similar to the Expand-Achrive we learned at the beginning of the article. Here, we used the -ArchiveFileName parameter name to specify the source of the compressed file while -TargetPath is used to write the destination path where we want to save the extracted items.

If you get any message saying that the 7Zip module is not recognized or not found, then you have to use the following command to install the 7Zip module first and then execute the command given above to unzip.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *