How to Compress With 7-Zip in PowerShell

How to Compress With 7-Zip in PowerShell

Many file archiving software with a high compression ratio is readily available in the market. One of which is the program called 7-Zip.

However, among the many advantages of 7-Zip, amongst other compression software, is that they can compress programmatically or by using a command-line interpreter like PowerShell.

This article will discuss how to compress with the 7-Zip software in PowerShell.

Compress With 7-Zip in PowerShell

Before attempting to compress with 7-Zip using PowerShell, we must ensure that 7-Zip is installed on our computer. Locate the installation directory and the executable file and assign the whole installation path in a PowerShell variable like the code below.

$7zipPath = "$env:ProgramFiles\7-Zip\7z.exe"

Let’s make the executable file look like it blends with our native PowerShell scripting environment by giving it an alias. If you have been a long-time PowerShell developer, you might know the Verb-Noun pair format as best practices when naming PowerShell commands.

We will use the Set-Alias command like the following code to create a new alias.

As you can see, we have used the Compress-7Zip command as the name of the executable file, which is in direct alignment with the mentioned best practice. But, of course, you can name it anything that you want.

Example Code:

Set-Alias Compress-7Zip $7ZipPath

Now let’s declare the file or folder that needs to be compressed and where we would send the compressed archive once done. To do this, assign the file to be compressed and its target location on each PowerShell variable.

Example Code:

$Source = "C:\Events\System.txt"
$Destination = "c:\PS\Events.zip"

Lastly, we can now start compressing with 7-Zip. We may refer to the official 7-Zip documentation link for all 7-Zip command line parameters.

However, to compress files, we can use the parameters below.

Example Code:

Compress-7zip a -mx=9 $Destination $Target

According to the official documentation, the parameter -mx=9 will set the compression level to 9, which would be the highest compression rate of the software.

Now that you can now use 7-Zip in PowerShell, it is also worth sharing that you will not need to worry if you don’t have 7-Zip installed. Windows PowerShell has its native command that will compress your files using the Compress-Archive command, and you can learn them more by clicking on this link.

Marion Paul Kenneth Mendoza avatar Marion Paul Kenneth Mendoza avatar

Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.

LinkedIn