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

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值