最近因需要对zip文件进行批量的压缩解压,遂想到用Powershell完成,正好可以借此熟悉一下基本用法。
通过自定义function可以很方便的完成我们想到的效果。
1. 解压文件
function Extract-Zip
{
param([string]$zipfilename, [string] $destination)
if(test-path($zipfilename))
{
$shellApplication = new-object -com shell.application
$zipPackage = $shellApplication.NameSpace($zipfilename)
$destinationFolder = $shellApplication.NameSpace($destination)
$destinationFolder.CopyHere($zipPackage.Items())
}
}
使用方法:
# extract all files from myzip.zip file to a directory
extract-zip c:\demo\myzip.zip c:\demo\destination
# extract all files from a list of zip files to a directory
dir c:\demo\*.zip | foreach-object { extract-zip $_.fullname c:\demo\destination }
2. 压缩文件
function Add-Zip
{
param([string]$sourcefiles, [string]$zipfilename)
dir $sourcefiles | foreach-object {
if(!$zipfilename) {
$zipfile = $_.FullName + ".zip";
}
else {
$zipfiles = $zipfilename;
}
if(!(test-path($zipfile))) {
set-content $zipfile ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18));
(dir $zipfile).IsReadOnly = $false;
}
$shellApplication = new-object -com shell.application;
$zipPackage = $shellApplication.NameSpace($zipfile);
$zipPackage.CopyHere(($_.FullName));
}
}
使用方法:
# add files to myzip.zip file
add-zip c:\demo\*.csv c:\demo\myzip.zip
# add files to zip files one by one (abc01.csv -> abc01.csv.zip)
add-zip c:\demo\*.csv
以上function 以及使用方法在windows xp, powershell v2.0 环境上测试通过。
get-host
参考资料:
Compress Files with Windows PowerShell then package a Windows Vista Sidebar Gadget