close
no thumb

Powershell One Liner – Easy Directory Zipping

Powershell One Liner - Easy Directory ZippingFor me one of most common tasks in Powershell is zipping or extracting files. Whether you’re backing up a few config files before pushing an updated version, or unzipping gigs of log files, dealing with zip files is an ever present task. In the early days of Powershell what I and many others used was the Shell.Application COM Object. For very basic functions, it worked fine.

New-Object -ComObject Shell.Application Zip

$shell = new-object -com shell.application
$zipPackage = $shell.NameSpace($zipfilename)
$files = get-childitem -Filter "$filter" -recurse
foreach($file in $files) 
    { 
        $zipPackage.CopyHere($file.FullName)
        Start-sleep -milliseconds 500
    }

The problem I found was that if you were dealing with very large zip files this method would often fail, and it often seemed much slower. Most likely this is due to the fact that is leveraging the Explorer Shell. I used DotNetZip for a number of years, and still find it to be a quality library, but I’m always looking for an opportunity to reduce dependency on non-native libraries.

If you have .NET 4.5 installed on your systems you can now leverage the .NET Compression library in your scripts. Not only is it very fast, but you can zip an entire directory in one line of code.

Add-Type -As "System.IO.Compression.FileSystem"
[System.IO.Compression.ZipFile]::CreateFromDirectory( "E:\MyDirectory", "E:\Archive\MyDirectory.zip", "Optimal", $true )

 

Byron Pate

The author Byron Pate