【powershell】在powershell脚本里归档zip文件

来源:互联网 发布:731网络意思 编辑:程序博客网 时间:2024/06/06 07:04

1、使用powershell命令

function createZipFile($zipFilename, $sourceDirectory) {    # The minimum size of a .ZIP file is 22 bytes. Such empty zip file contains only an End of Central Directory Record (EOCD):[50,4B,05,06,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00]    set-content $zipFilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))    (dir $zipFilename).IsReadOnly = $false     # return $zipFilename(Folder Object)    $shell = new-object -com shell.application    $zip = $shell.NameSpace($zipFilename)    # create zip file move $sourceDirectory to $zipFilename    $zip.MoveHere($sourceDirectory)    do {sleep -Seconds 1} until (!(Test-Path $sourceDirectory))}

(“PK” + [char]5 + [char]6 + (“$([char]0)” * 18)) 表示zip文件的最小size。
“PK”表示zip文件的Magic number (Magic number)。
0x504B0506(PK\05\06)表示zip文件的End of central directory record(EOCD)结束标志(Zip Format)。
zip是一个folder对象,调用zip的MoveHere方法将$sourceDirectory移动到$zipz中,并删除$sourceDirectory,(CopyHere不删除源文件)

2、使用Powershell 3 and .NET 4 . 5

function createZipFile($zipFilename, $sourceDirectory) {   Add-Type -Assembly System.IO.Compression.FileSystem   $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal   [System.IO.Compression.ZipFile]::CreateFromDirectory($sourceDirectory, $zipFilename, $compressionLevel, $false)}

使用.net提供的ZipFile Class
第二个参数一定是一个目录名,文件名不知道怎么支持,待研究。

3、使用7-zip的命令

$7ZipInstallPath = ([Regex]::Replace(((Get-ItemProperty ("HKLM:\SOFTWARE\" + "7-Zip")).Path), '(^.*)\\$', '$1'))function createZipFile($zipFilename, $sourceDirectory){    $zipExePath = "$($7ZipInstallPath)\7z.exe";    [Array]$arguments = "a", "-tzip", "$aZipfile", "$aDirectory", "-r";    & $zipExePath $arguments;}

先获取到7-zip的安装路径,然后在程序里调用7-zip.exe
还可以$zipExePath = “$($Env:ProgramFiles)\7-Zip\7z.exe”但是这样不知道支不支持把7-zip安装到非系统盘。
a:Add files to archive
-tzip:Set type of archive
r:Recurse subdirectories

参考

http://stackoverflow.com/questions/1153126/how-to-create-a-zip-archive-with-powershell

0 0