How to Zip File using PowerShell
Introduction
In this article we will look at how you can archive files using PowerShell.
Problem
When working with PowerShell often we are getting information about servers, sql instances or from logs, this information could end up being quite large so its useful to be able to compress it.
Solution
The PowerShell module Microsoft.PowerShell.Archive
has the function Compress-Archive
which does exactly what we want. The Microsoft docs describe this module as “Creates a compressed archive, or zipped file, from specified files and directories.”
Let’s take a look at some examples.
Example 1: Compress the results of a sql query
In this example we will grab some information from a sql server, write it out to a text file and then finally zip that text file.
$instanceNames=("servera.domain1.com\MSSQLSERVER01","servera.domain2.com\MSSQLSERVER01")
$query = "select @@SERVERNAME, @@VERSION"
foreach($instance in $instanceNames)
{
Invoke-SqlCmd –ServerInstance $instance -Query $query | Out-File results.txt -Append
}
Compress-Archive .\results.txt -DestinationPath results.zip
As you can see in its most simplest form your just passing a file or files to the compress archive function and then a destination file name, in this case results.zip Lets look at another example.
Example 2: Compress the specified root folder
In this example we specify a path, the paths root folder and all its files will be zipped up.
Compress-Archive -Path "C:\Users\Documents\settings" -DestinationPath "C:\Users\Documents\settings\settings.zip"
So you can see the results of the command are a zip in the directory we specified.

And if we take a look at the contents of the zip you will see it includes the files and they have been put into the root folder that was specified which was “settings”.

Conclusion
PowerShell makes working with zip archives really easy with the Microsoft.PowerShell.Archive
module. This is all built in and easily accessible, so you don’t need to worry about installing or importing any additional modules.
Here we explored some simple examples of querying a sql server, creating a text file and zipping that file, and then we zipped a whole directory including all its files. The MS Docs have a lot of good examples so be sure to check them out if you need to know more.
As always you can pull up the examples of a function using the get help command!
Get-Help Compress-Archive -Examples