Zip压缩/解压缩(文件夹)

#PS2.0压缩为.zip文件:

$zip = "D:audit_log est.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同样支持对整个文件夹的压缩,所以以上代码可以更改为如下:

$zip = "D:audit_log est.zip"
New-Item $zip -ItemType file
$shellApplication = new-object -com shell.application
$zipPackage = $shellApplication.NameSpace($zip)
$zipPackage.CopyHere("D:audit_logabc")

#如果把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: est,目录
Unzip-File -ZipFile E:a.zip -TargetFolder e: est

 
################################################

#PS3.0调用.Net4.5内置类(ZipFile)压缩/解压.zip:
#压缩
$sourcefile = "d: estackinfo"
$target = "d: estackinfo.zip"
[void][System.Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem')
[System.IO.Compression.ZipFile]::createfromdirectory($sourceFile, $target)

#解压
$sourcefile = "d: estackinfo.zip"
$target = "d: estackinfo"
[void][System.Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem')
[System.IO.Compression.ZipFile]::ExtractToDirectory($sourceFile, $target)

[System.IO.Compression.ZipFile]|gm -static

原文地址:https://www.cnblogs.com/dreamer-fish/p/3299068.html