Zip压缩解压缩(文件夹)

Zip压缩解压缩(文件夹),第1张

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

#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同样支持对整个文件夹的压缩,所以以上代码可以更改为如下:

$zip = "D:\audit_log\test.zip"
New-Item $zip -ItemType file
$shellApplication = new-object -com shell.application
$zipPackage = $shellApplication.NameSpace($zip)
$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"
[void][System.Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem')
[System.IO.Compression.ZipFile]::ExtractToDirectory($sourceFile, $target)

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

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/587336.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-12
下一篇 2022-04-12

发表评论

登录后才能评论

评论列表(0条)

保存