【powershell】在powershell脚本里归档zip文件
2015-10-15 10:22
976 查看
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相关文章推荐
- 0day-简单动态获取API(shellcode)分析NO.1
- 常用的bash shell脚本 一些常用的运维管理方法
- Shell脚本小技巧
- shell脚本编程-例子_服务器存活监控
- linux中shell变量$#,$@,$0,$1,$2的含义解释
- simple introduction for bash
- shell内部命令和外部命令
- linux shell — 3.linux的档案属性和目录配置(2)
- HDFS File System Shell Guide
- linux shell 使用出现问题(1)
- linux shell实现随机数几种方法分享(date,random,uuid)
- shell之图形进度条
- Shell在大数据的魅力时代:从一点点思路百度大数据面试题
- shell编程的MD5校验
- shell 中创建临时文件(随机文件名)的方法总结
- Android开发工具—adb shell命令
- shell——按指定列排序
- bash的位置变量和特殊变量
- bash中的算术运算
- bash文本查看及处理工具