Powershell是運行於Windows平台上腳本,應用廣泛。這里我們來實現ZIP壓縮文件。首先,這里引用開源ICSharpCode.SharpZipLib.dll ,所以您得先下載這個程序集。
把下面的內容寫成一個CreateZipFile.ps1文件:
##############################################################################
##
## CreateZipFile
##
## by Peter Liu (http://wintersun.cnblogs.com)
##
##############################################################################
<#
.SYNOPSIS
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/
.EXAMPLE
dir testdata\*.txt | .\CreateZipFile data.zip h:\Dev\bin\ICSharpCode.SharpZipLib.dll
.EXAMPLE
"readme.txt" | .\CreateZipFile docs.zip h:\Dev\bin\ICSharpCode.SharpZipLib.dll
Copies readme.txt to docs.zip
#>
param(
## The name of the zip archive to create
$ZipName = $(throw "Specify a zip file name"),
## The path to ICSharpCode.SharpZipLib.dll
$LibPath = $(throw "Specify the path to SharpZipLib.dll")
)
Set-StrictMode -Version Latest
## 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 =
New-Object ($namespace -f "ZipOutputStream") ([IO.File]::Create($zipName))
$zipFullName = (Resolve-Path $zipName).Path
[byte[]] $buffer = New-Object 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( (Get-Location).Path + "\" )
$zipName = ([string] $file) -replace $replacePath,""
## Create the zip entry, and add it to the file
$zipEntry = New-Object ($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()
如果您是第一次執行ps1文件在Powershell的控制台,還需要執行:
Set-ExecutionPolicy RemoteSigned
然后例如我們執行:
dir testdata\*.txt | .\CreateZipFile data.zip h:\Dev\bin\ICSharpCode.SharpZipLib.dll
把當目錄下testdata文件夾中的所有txt文件壓縮到data.zip文件。
軟件工程中我們經常需要做自動化處理,使用腳本來壓縮文件是常見的操作。
希望對您軟件開發有幫助。
關於PowerShell,請看TechNet
作者:Petter Liu
出處:http://www.cnblogs.com/wintersun/
本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。
該文章也同時發布在我的獨立博客中-Petter Liu Blog。