Zip and Unzip with PowerShell 5

October 30, 2015 at 8:27 am in PowerShell by Florent

Fastest

For a specific reason of automation, I need to ZIP and UNZIP some static files automatically. I’m running Windows 10, so, PowerShell 5 is available natively:

image

In this version of PowerShell, if you type Get-Module –ListAvailable, you will be able to see the following list:

image

As you can see, a new module is available, named Microsoft.PowerShell.Archive with two commands Compress-Archive and Expand-Archive. Import this module to use it:

image

So now, to compress a single file, you can do it natively, without using an external module. I will compress a file located on my desktop, with the following command:

Compress-Archive -Path C:\Users\flore\Desktop\IP.bat -DestinationPath C:\Users\flore\Desktop\IP.zip -CompressionLevel Fastest

image

You have 3 CompressionLevel:

  • Fastest
  • NoCompression
  • Optimal

To UNZIP the file, do the following:

Expand-Archive -Path C:\Users\flore\Desktop\IP.zip -DestinationPath C:\Users\flore\Downloads\

image

You can use the switch –Force to overwrite files.

If you want to zip multiple files, you can do it with the following command:

Get-ChildItem -Path C:\Users\flore\Downloads\WS | Compress-Archive -DestinationPath C:\Users\flore\Downloads\WS.zip -CompressionLevel Optimal

image

I created my script based on these 2 commands and I scheduled a task to execute it every days. I hope that this small article will help you in your automation Sourire