#PS2.0壓縮為.zip檔案:
$zip = "D:\audit_log\test.zip"
New-Item $zip -ItemType file
$shellApplication = new-object -com shell.application
$zipPackage = $shellApplication.NameSpace($zip)
$files = gci D:\audit_log\*.log
foreach($file in $files)
{
$zipPackage.CopyHere($file.FullName) #MoveHere() 将檔案移動到.zip壓縮包
Start-sleep -seconds 5
}
#注:該腳本通過異步方式将檔案添加到.zip壓縮包,故無法判斷目前檔案是否已添加到壓縮包成功,當目前的檔案還未完全添加到.zip壓縮包時,下一個檔案再添加時會出現錯誤,無法添加到壓縮包,是以可能會丢失檔案,如果能确定檔案壓縮時長,可以使用Start-Sleep方法進行延時
CopyHere同樣支援對整個檔案夾的壓縮,是以以上代碼可以更改為如下:
$zipPackage.CopyHere("D:\audit_log\abc")
#如果把CopyHere改為MoveHere,将會在壓縮完成後删除源檔案
#将需要壓縮的檔案全部放到目錄abc下,然後對abcc整個目錄進行壓縮
###############################
PS2.0解壓zip檔案:
Function Unzip-File()
param([string]$ZipFile,[string]$TargetFolder)
#確定目标檔案夾必須存在
if(!(Test-Path $TargetFolder))
{mkdir $TargetFolder}
$shellApp = New-Object -ComObject Shell.Application
$files = $shellApp.NameSpace($ZipFile).Items()
$shellApp.NameSpace($TargetFolder).CopyHere($files)
#将zip檔案E:\a.zip解壓到e:\test,目錄
Unzip-File -ZipFile E:\a.zip -TargetFolder e:\test
################################################
#PS3.0調用.Net4.5内置類(ZipFile)壓縮/解壓.zip:
#壓縮
$sourcefile = "d:\test\backinfo"
$target = "d:\test\backinfo.zip"
[void][System.Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem')
[System.IO.Compression.ZipFile]::createfromdirectory($sourceFile, $target)
#解壓
$sourcefile = "d:\test\backinfo.zip"
$target = "d:\test\backinfo"
[System.IO.Compression.ZipFile]::ExtractToDirectory($sourceFile, $target)
[System.IO.Compression.ZipFile]|gm -static