Creating a zipped/compressed folder in Windows using Powershell or the command line Creating a zipped/compressed folder in Windows using Powershell or the command line windows windows

Creating a zipped/compressed folder in Windows using Powershell or the command line


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.


Here's a couple of zip-related functions that don't rely on extensions: Compress Files with Windows PowerShell.

The main function that you'd likely be interested in is:

function Add-Zip{    param([string]$zipfilename)    if(-not (test-path($zipfilename)))    {        set-content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))        (dir $zipfilename).IsReadOnly = $false      }    $shellApplication = new-object -com shell.application    $zipPackage = $shellApplication.NameSpace($zipfilename)    foreach($file in $input)     {             $zipPackage.CopyHere($file.FullName)            Start-sleep -milliseconds 500    }}

Usage:

dir c:\demo\files\*.* -Recurse | Add-Zip c:\demo\myzip.zip

There is one caveat: the shell.application object's NameSpace() function fails to open up the zip file for writing if the path isn't absolute. So, if you passed a relative path to Add-Zip, it'll fail with a null error, so the path to the zip file must be absolute.

Or you could just add a $zipfilename = resolve-path $zipfilename at the beginning of the function.


As of PowersShell 5 there is a Compress-Archive cmdlet that does the task out of the box.