随笔 - 911  文章 - 5  评论 - 94  阅读 - 243万

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

posted on   momingliu11  阅读(2712)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示