These PowerShell scripts can be used to zip and unzip files.
Zip operates on file lists such as output from the Get-ChildItem cmdlet. You can set the zip file root folder by specifying the leading folder path to remove. The Where-Object cmdlet can be used for advanced filtering. This function does not zip empty folders. See the SharpZipLib wiki for examples of zipping empty folders. Also, this function does not work with files that are locked, such as log files that are being written.
The free SharpZipLib .NET Zip assembly is used for zip functionality. You'll need to download the assembly and load it into PowerShell to run the scripts. Note that after you download or copy the assembly locally, you may have to trust the assembly. To do this, right-click the assembly and trust (unblock) it. Other related info can be found the SharpZipLib wiki.
These PowerShell scripts were tested using SharpZipLib version 0.85.5.
Strong name: ICSharpCode.SharpZipLib, Version=0.85.5.452, Culture=neutral, PublicKeyToken=1b03e6acf1164f73function zip($zipFile, $leadingFolderPathToRemove)
{
begin
{
$zip = [icSharpCode.sharpZipLib.zip.zipFile]::create($zipFile)
$zip.beginUpdate()
#add trailing backslash if necessary
$leadingFolderPathToRemove = (join-path $leadingFolderPathToRemove '\')
}
process
{
#remove leading folder path from file name
$file = $_.fullName.remove(0, $leadingFolderPathToRemove.length)
$zip.add($_.fullName, $file)
}
end
{
$zip.commitUpdate()
'{0} files zipped' -f $zip.count
$zip.close()
}
}
function unzip($zipFile, $unzipToFolder)
{
$zip = new-object icSharpCode.sharpZipLib.zip.fastZip
$zip.extractZip($zipFile, $unzipToFolder, $null)
}
Examples
loadAssembly c:\lib\sharpZipLib\ICSharpCode.SharpZipLib.dll
#zip all files from folder c:\code\web\ into c:\temp\web.zip
gci c:\code\web\* -include *.* -recurse -force | zip c:\temp\web.zip c:\code\web\
#only files modified 11-22-2009 or later
gci c:\code\web\* -include *.* -recurse -force |
where {$_.lastWriteTime -ge [dateTime]"11-22-2009 00:00"} |
zip c:\temp\web.zip c:\code\web\
#exclude files: *.csproj*, *.pdb, *.refresh, *.sln, *.suo
#exclude folders: debug, obj, release, properties
$excludeRegex = '(\.(csproj(.*)|pdb|refresh|sln|suo)$)|(\\(debug|obj|release|properties)(\\|$))'
gci c:\code\web\* -include *.* -recurse -force |
where {$_.fullName -notMatch $excludeRegex} |
zip c:\temp\web.zip c:\code\web\
#unzip c:\temp\web.zip into folder c:\temp\unzip\web\
unzip c:\temp\web.zip c:\temp\unzip\web