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

posted on 2012-11-30 21:28  PetterLiu  阅读(4535)  评论(0编辑  收藏  举报