Recently, I recalled the extent to which you had to go to compress a set of files on PowerShell.
In older versions of PowerShell, for example, you might have had something like this:

… and as you can see, error handling for existing files, wasn’t great – you had to script a Test-Path
before running the compression to see if the file already existed.
In more recent versions, Microsoft have made life much easier with the Compress-Archive
command. Not only can files be zipped and compressed, but we can also add files to the zip. Here are a few examples:
Firstly, here are a list of directories:
PS /Users/markpatton/repos/codesamples> ls -l total 8 -rw-r--r-- 1 markpatton staff 124 7 Mar 18:55 README.md drwxr-xr-x 6 markpatton staff 192 14 Mar 09:19 az_barracuda-waf drwxr-xr-x 5 markpatton staff 160 7 Mar 18:55 az_bastion drwxr-xr-x 4 markpatton staff 128 14 Mar 09:19 az_keyvault drwxr-xr-x 4 markpatton staff 128 14 Mar 09:49 az_management
Lets zip the az_management
directory to a file named mycompressedfiles.zip
:
Compress-Archive -Path ./az_management/ -CompressionLevel Optimal -DestinationPath ./mycompressedfiles.zip
Now, let me demonstrate how we can add directories or files to an existing compressed file, using the --update or -u
switch, by adding az_keyvault
to mycompressfiles.zip
:
Compress-Archive -Path ./az_keyvault/ -Update -DestinationPath ./mycompressedfiles.zip
Next step is to demonstrate how we can expand (or unzip) the compressed file and prove that we have been able to compress a directory, and update the compressed file with additional directories:
PS /Users/markpatton/repos/codesamples> Expand-Archive -Path ./mycompressedfiles.zip -DestinationPath ./expanded_directory PS /Users/markpatton/repos/codesamples> ls README.md az_bastion az_management mycompressedfiles.zip az_barracuda-waf az_keyvault expanded_directory PS /Users/markpatton/repos/codesamples> ls -l ./expanded_directory/ total 0 drwxr-xr-x 3 markpatton staff 96 14 Mar 13:39 az_keyvault drwxr-xr-x 4 markpatton staff 128 14 Mar 13:39 az_management PS /Users/markpatton/repos/codesamples> ls -lr ./expanded_directory/az_keyvault/ total 0 drwxr-xr-x 3 markpatton staff 96 14 Mar 13:39 scripts
Finally, there are 3 different Compression settings you can choose from:
- Fastest. Use the fastest compression method available to reduce processing time. Faster compression can result in larger file sizes.
- NoCompression. Doesn’t compress the source files.
- Optimal. Processing time is dependent on file size.