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\Compress.zip";
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!
<# .Synopsis Compresses each of the folders in the list of candidate folders, producing a ZIP file outpuut #> function CompressCandidateFolders { param ( [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"; } else { [System.IO.Compression.ZipFile]::CreateFromDirectory($_, $filename, [System.IO.Compression.CompressionLevel]::Optimal, $true); } $percentComplete = $percentComplete + $percentPerScript; if ($percentComplete -gt 100) { $percentComplete = 100; } } }