Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a zip archive with PowerShell?

People also ask

How do I create an archive in PowerShell?

To create an archive that includes the root directory, and all its files and subdirectories, specify the root directory in the Path without wildcards. For example: -Path C:\Reference. To create an archive that excludes the root directory, but zips all its files and subdirectories, use the asterisk ( * ) wildcard.

How do I create an archive zip file?

Press and hold (or right-click) the file or folder, select (or point to) Send to, and then select Compressed (zipped) folder. A new zipped folder with the same name is created in the same location.

How do I zip a file in PowerShell script?

The cmdlet Compress-Archive and Expand-Archive have been introduced in PowerShell 5 and allow you to easily zip (compress) and unzip (extract) archives on the the command line. Using these cmdlets can save time and disk space when packaging up log files or folders for safe keeping.


PowerShell v5.0 adds Compress-Archive and Expand-Archive cmdlets. The linked pages have full examples, but the gist of it is:

# Create a zip file with the contents of C:\Stuff\
Compress-Archive -Path C:\Stuff -DestinationPath archive.zip

# Add more files to the zip file
# (Existing files in the zip file with the same name are replaced)
Compress-Archive -Path C:\OtherStuff\*.txt -Update -DestinationPath archive.zip

# Extract the zip file to C:\Destination\
Expand-Archive -Path archive.zip -DestinationPath C:\Destination

A pure PowerShell alternative that works with PowerShell 3 and .NET 4.5 (if you can use it):

function ZipFiles( $zipfilename, $sourcedir )
{
   Add-Type -Assembly System.IO.Compression.FileSystem
   $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
   [System.IO.Compression.ZipFile]::CreateFromDirectory($sourcedir,
        $zipfilename, $compressionLevel, $false)
}

Just pass in the full path to the zip archive you would like to create and the full path to the directory containing the files you would like to zip.


If you head on over to CodePlex and grab the PowerShell Community Extensions, you can use their write-zip cmdlet.

Since

CodePlex is in read-only mode in preparation for shutdown

you can go to PowerShell Gallery.


A native way with latest .NET 4.5 framework, but entirely feature-less:

Creation:

Add-Type -Assembly "System.IO.Compression.FileSystem" ;
[System.IO.Compression.ZipFile]::CreateFromDirectory("c:\your\directory\to\compress", "yourfile.zip") ;

Extraction:

Add-Type -Assembly "System.IO.Compression.FileSystem" ;
[System.IO.Compression.ZipFile]::ExtractToDirectory("yourfile.zip", "c:\your\destination") ;

As mentioned, totally feature-less, so don't expect an overwrite flag.

UPDATE: See below for other developers that have expanded on this over the years...