[PowerShell] How to use 7Zip to zip or unzip a folder

1 minute read

There are certain conditions where PowerShell Expand-Archive or Compress-Archive cmdlets could not be used to zip or unzip a folder. In my scenario, I have a deep nested files structure which Expand-Archive could not unzip the files successfully. It throws me “Path too long” error message.

If PowerShell Expand-Archive or Compress-Archive could not let you unzip or zip the file, you could use 7-Zip to do so.

  1. Download 7-zip from: https://www.7-zip.org/download.html
  2. Install 7-Zip into a local computer

Result : 7-zip has been installed. The 7-Zip file will be installed in C:\Program Files\7-Zip path.

To zip a file

Set-Alias -Name 7zip -Value "$env:ProgramFiles\7-Zip\7z.exe"
$zipfilePath = "C:\PowerShellExercise\ZipOrUnzipFile\Files"
$destinationUnzipPath = "C:\PowerShellExercise\ZipOrUnzipFile"
7zip a $zipfilePath "-o$($destinationUnzipPath)" -y 

To Unzip a file

Set-Alias -Name 7zip -Value "$env:ProgramFiles\7-Zip\7z.exe"
$zipfilePath = "C:\PowerShellExercise\ZipOrUnzipFile\Files.zip"
$destinationUnzipPath = "C:\PowerShellExercise\ZipOrUnzipFile\Files"
7zip x $zipfilePath "-o$($destinationUnzipPath)" -y

Note: We use Set-Alias cmdlet to give another name for the given value. In this case, we rename 7z.exe path location to be 7zip so that it is easy and readable to call the 7zip executable file.

Parameters:
a - to zip (compress) a folder
x - to unzip (extract) a folder