Now in PowerShell 5.0 we have the Compress-Archive and Expand-Archive cmdlets.
Prior to PowerShell 5.0 there is no built-in cmdlet for zipping files, but in PowerShell 3/4 with .Net 4.5 (or greater) there is an option to use the classes ZipFile and ZipArchive.
To use these new classes, use Add-Type to import the System.IO.Compression.FileSystem assembly, like so:
Add-Type -As System.IO.Compression.FileSystem [IO.Compression.ZipFile]
::CreateFromDirectory( ('C:work\demo'), "demo.zip", "Optimal", $true )
To make this a little easier to type use the Zipfile functions (from Joel Bennett/poshcode.org), which you can download here.
Syntax
New-Zipfile [-ZipFilePath] object [-InputObject] string[]
[-Append] [-compression {Optimal | Fastest | nocompression}] [CommonParameters]
key
-ZipFilePath The path of the zip to create.
-InputObject Items that we want to add to the ZipFile.
-Append Append to an existing zip file instead of overwriting it.
-Compression The compression level (defaults to Optimal):
Optimal - The compression operation should be optimally compressed, even if
the operation takes a longer time to complete.
Fastest - The compression operation should complete as quickly as possible,
even if the resulting file is not optimally compressed.
NoCompression - No compression should be performed on the file.
CommonParameters:
-Verbose, -Debug, -ErrorAction, -ErrorVariable, -WarningAction, -WarningVariable,
-OutBuffer, -PipelineVariable, -OutVariable.
Expand a zip file to a folder:
Syntax
Expand-ZipFile [-FilePath] Object [[-OutputPath] Object] [-Force] [CommonParameters]
Key
-FilePath The path of the zip file that needs to be extracted.
-OutputPath The path where we want the output folder to end up.
-Force Name the resulting folder the same as the archive.
CommonParameters:
-Verbose, -Debug, -ErrorAction, -ErrorVariable, -WarningAction, -WarningVariable,
-OutBuffer, -PipelineVariable, -OutVariable.
To make these Zip functions available all the time, add them to your PowerShell profile.
Examples
Zip the folder C:work\demo:
PS C:\> New-Zipfile 'c:\scripts\demo.zip' 'C:work\demo'
Un-Zip the file backup.zip:
PS C:\> Expand-Zipfile 'c:\scripts\backup.zip'
“Since time is the one immaterial object which we cannot influence--neither speed up nor slow down, add to nor diminish--it is an imponderably valuable gift” ~ Maya Angelou
Related PowerShell Cmdlets:
Functions and Filters - Named blocks of code.