Discussion
When transporting or archiving files, it is useful to store those files in an archive. ZIP archives are the most common type of archive, so it would be useful to have a script to help manage them.
For many purposes, traditional commandline ZIP archive utilities may fulfill your needs. If they do not support the level of detail or interaction that you need for administrative tasks, a more programmatic alternative is attractive.
Example 177 lets you create ZIP archives simply by piping files into them. It requires that you have the SharpZipLib installed, which you can obtain from http:// www.icsharpcode.net/OpenSource/SharpZipLib/ .
Example 177. NewZipFile.ps1
############################################################################## ## ## NewZipFile.ps1 ## ## Create a Zip file from any files piped in. Requires that ## you have the SharpZipLib installed, which is available from ## http://www.icsharpcode.net/OpenSource/SharpZipLib/ ## ## ie: ## ## PS >dir *.ps1 | NewZipFile scripts.zip d:\bin\ICSharpCode.SharpZipLib.dll ## PS >"readme.txt" | NewZipFile docs.zip d:\bin\ICSharpCode.SharpZipLib.dll ## ##############################################################################
Example 177. NewZipFile.ps1 (continued)
param( $zipName = $(throw "Please specify the name of the file to create."), $libPath = $(throw "Please specify the path to ICSharpCode.SharpZipLib.dll.") )
## Load the Zip library [void] [Reflection.Assembly]::LoadFile($libPath) $namespace = "ICSharpCode.SharpZipLib.Zip.{0}"
## Create the Zip File $zipName =
$executionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($zipName) $zipFile = NewObject ($namespace f "ZipOutputStream") ([IO.File]::Create($zipName)) $zipFullName = (ResolvePath $zipName).Path
[byte[]] $buffer = NewObject byte[] 4096
## Go through each file in the input, adding it to the Zip file ## specified foreach($file in $input) {
## Skip the current file if it is the zip file itself if($file.FullName eq $zipFullName) {
continue }
## Convert the path to a relative path, if it is under the current location $replacePath = [Regex]::Escape( (GetLocation).Path + "\" ) $zipName = ([string] $file) replace $replacePath,""
## Create the zip entry, and add it to the file $zipEntry = NewObject ($namespace f "ZipEntry") $zipName $zipFile.PutNextEntry($zipEntry)
$fileStream = [IO.File]::OpenRead($file.FullName) [ICSharpCode.SharpZipLib.Core.StreamUtils]::Copy($fileStream, $zipFile, $buffer) $fileStream.Close()
}
## Close the file $zipFile.Close()