Compressing directories to ZIP from PowerShell

A quick note to self about compressing folders using PowerShell, basically the trick is to use the ZipFile class from the System.IO.Compression.FileSystem assembly:

$directory = "C:\Path\To\Directory\To\Compress";
$filename = "C:\Path\To\Directory\To\";

Add-Type -Assembly "System.IO.Compression.FileSystem";
[System.IO.Compression.ZipFile]::CreateFromDirectory($directory, $filename, [System.IO.Compression.CompressionLevel]::Optimal, $true);

If you've got a a list of candidate folders (string[] in the code I've lifted this example from), you can iterate over it using ForEach-Object and ZIP each directory in $candidateFolders in one fell swoop, with a bit of progress-bar feedback thrown in for good measure!

Compresses each of the folders in the list of candidate folders, producing a ZIP file outpuut
function CompressCandidateFolders
        [parameter(Mandatory=$true)] [string[]] $candidateFolders

    $activityDescription = "Compressing folders";
    $candidateFolderCount =  If ($candidateFolders.Length -eq 0) { 1 } else { $candidateFolders.Length }
    $percentPerScript =  [int](100 / $candidateFolderCount);
    $percentComplete = 0;

    $candidateFolders | ForEach-Object {
        $filename = $_ + ".zip";
        Write-Progress -Activity $activityDescription -CurrentOperation "Zipping $_" -PercentComplete $percentComplete;

        if ([System.IO.File]::Exists($filename) -eq $true)
            echo "ZIP file for $filename already exists, skipping";
            [System.IO.Compression.ZipFile]::CreateFromDirectory($_, $filename, [System.IO.Compression.CompressionLevel]::Optimal, $true);

        $percentComplete = $percentComplete + $percentPerScript;
        if ($percentComplete -gt 100)
            $percentComplete = 100;

About Rob

I've been interested in computing since the day my Dad purchased his first business PC (an Amstrad PC 1640 for anyone interested) which introduced me to MS-DOS batch programming and BASIC.

My skillset has matured somewhat since then, which you'll probably see from the posts here. You can read a bit more about me on the about page of the site, or check out some of the other posts on my areas of interest.

No Comments

Add a Comment