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,
- For
$target = "D:\temp3\test3"
, the 'test3' will be the root directory in the compressed file. - For
$target = "D:\temp3\test3\*"
, the 'test3' will not be the root directory. Only the sub-directories and files inside 'test3' will be compressed. - For
$target = "D:\temp3\test3*"
, all files and directories that starts with 'test3' will be in the compressed file.
FAQ
-
Sometimes, the compressed file is too big to be transferred around, you may want to split it into multiple smaller files with
-v
switch.In the console help message for
-v
usage,-v{Size}[b|k|m|g] : Create volumes
To create multiple smaller 100MB compressed files, append
-v100m
and the$cmd
will be look like this,$cmd = """$compressor"" a ""$dest"" ""$target"" -p1234 -mhe -v100m"
-
To test the compressed file, we use
t
command,$cmd = """$compressor"" t ""$dest"" -p1234"
Jump to #POWERSHELL blog
Author
Lau Hon Wan, software developer.