title: Compress files to Zip with Powershell
date: 2014-12-15 14:14:00 +0200 +0200
draft: false
author: John

I have seen a lot of people writing PowerShell scripts to compress files or folders by using external file compression programs. Often Winrar, 7-Zip or something similar is used since PowerShell does not have any built in cmdlet to do this (not until version 5 at least).

There is however a pretty simple way of doing this with only PowerShell. This is how.

# First we add the .Net framework class needed for file compression.
Add-Type -As System.IO.Compression.FileSystem
# Then we need a variable of the type System.IO.Compression.CompressionLevel. 
# The options for compression level are "Fastest", "Optimal" and "NoCompression".
[System.IO.Compression.CompressionLevel]$compression = "Optimal"
# Which file do you want to compress?
$file = 'C:\temp\file.txt'
# Set the path to where you want the zip file to be created.
$zippath = 'C:\temp\file.zip'
# Open the zip file and set the mode. Options for mode are "Create", "Read" and "Update".
$ziparchive = [System.IO.Compression.ZipFile]::Open( $zippath, "Update" )
# The compression function likes relative file paths, so lets do that.
$relativefilepath = (Resolve-Path $file -Relative).TrimStart(".\")
# This is where the magic happens. 
# Compress the file with the variables you just created as parameters.
$null = [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($ziparchive, $file, $relativefilepath, $compression)
# Release the zip file. 
# Otherwise the file will still be in read only if you are using Powershell ISE.

Read more about these features at MSDN.