Welcome to ciysys blog

Using 7z in Powershell

Published on: 2nd Mar 2023

Explanation

Powershell comes with Compress-Archive cmdlet to compress files and directories. But, it does not allows you to encrypt the compressed file with a password. In this case, you might want to consider use 7z to do the job.

7z is an open source program and the installer can be downloaded from the following URL:

https://www.7-zip.org/download.html

After you have installed it, you may use it to compress file and directory.

For example, you want to compress the 'test3' directory and the script will be something like this:

$compressor = "C:\program files\7-Zip\7z.exe"
$dest = "D:\temp3\myZipFile.7z"
$target = "D:\temp3\test3"
$cmd = """$compressor"" a ""$dest"" ""$target"" "
cmd.exe /c $cmd

This is quite easy and straight forward. Let's try to encrypt the compressed file with a password by using -p parameter and 1234 is the password.

$compressor = "C:\program files\7-Zip\7z.exe"
$dest = "D:\temp3\myZipFile.7z"
$target = "D:\temp3\test3"
$cmd = """$compressor"" a ""$dest"" ""$target"" -p1234 "
cmd.exe /c $cmd

By default, -p will caused the compressed file to be encrypted and it allows anyone to view the file and directory name (i.e., the directory structure is viewable). But, decompressing it requires the correct password.

If you have any senstive data and you don't want anyone to view the file and directory names in the compressed file, you have to add -mhe switch and the script will be look like this,

$compressor = "C:\program files\7-Zip\7z.exe"
$dest = "D:\temp3\myZipFile.7z"
$target = "D:\temp3\test3"
$cmd = """$compressor"" a ""$dest"" ""$target"" -p1234 -mhe"
cmd.exe /c $cmd

Use cases

From the user point of view, there are 3 expectations for the compressed file content,

  1. For $target = "D:\temp3\test3", the 'test3' will be the root directory in the compressed file.
  2. For $target = "D:\temp3\test3\*", the 'test3' will not be the root directory. Only the sub-directories and files inside 'test3' will be compressed.
  3. For $target = "D:\temp3\test3*", all files and directories that starts with 'test3' will be in the compressed file.

FAQ

Jump to #POWERSHELL blog

Author

Lau Hon Wan, software developer.