PowerShell-压缩解压缩文件
- 缘起
- 压缩文件
- 1.调用第三方工具自带命令
- 2. PowerShell命令压缩
- 解压缩文件
- 1. PS命令解压
- 2. Windows内置解压
- 3. 调用COM对象
- 附:查看PowerShell版本方法
缘起
前几天下载资料,打开之后发现其中有二百多个文件且每个都有单独的压缩处理,使用起来略有不便。于是用PowerShell改善了下生活,免除手动解压,记录一下代码以及扩展。
压缩文件
1.调用第三方工具自带命令
未收录,局限性太大。将来可能会整理一下。
2. PowerShell命令压缩
前提:PS V5以上。
Compress-Archive -Path C:\Users\Documents\UiPath\2 -DestinationPath C:\Users\Documents\UiPath\2\1.zip
解压缩文件
1. PS命令解压
前提:PS V5以上。
Expand-Archive -Path C:\Users\Documents\UiPath\2\1.zip -DestinationPath C:\Users\Documents\UiPath\2
- 如果担心文件覆盖问题可添加参数 -Force:$Overwrite
2. Windows内置解压
前提:需要.net 4.5以上
$BackUpPath = "C:\Users\Documents\UiPath\2\1.zip"
$Destination = "C:\Users\Documents\UiPath\2"
Add-Type -assembly "system.io.compression.filesystem"
[io.compression.zipfile]::ExtractToDirectory($BackUpPath, $destination)
3. 调用COM对象
前提:PS版本2.0或.net 4.5以上
$shell = New-Object -ComObject shell.application
$zip = $shell.NameSpace("C:\Users\Documents\UiPath\2\1.zip")
MkDir("C:\Users\Documents\UiPath\2")
foreach ($item in $zip.items()) {
$shell.Namespace("C:\Users\Documents\UiPath\2").CopyHere($item)
}
此方式有大佬已经写好函数,此处可去往原文,原理相同,亦记录在案:
function UnzipFile([string]$sourceFile, [string]$targetFolder)
{
if(!(Test-Path $targetFolder))
{
mkdir $targetFolder
}
$shellApp = New-Object -ComObject Shell.Application
$files = $shellApp.NameSpace($souceFile).Items()
$files|%{if (Test-Path ("$targetFolder/{0}" -f $_.name )){Remove-Item ("$targetFolder/{0}" -f $_.name) -Force -Recurse}}
$shellApp.NameSpace($targetFolder).CopyHere($files)
}
UnzipFile "C:\Users\Documents\UiPath\2\1.zip" "C:\Users\Documents\UiPath\2"
- PS: 我遇到的问题最后也是使用这个函数去做的,不过外面加上了循环结构,二百多个压缩文件就乖乖地自己解压了,还是有点小爽的,函数以外的代码如下:
cd "C:\Users\Documents\UiPath\2"
foreach ($i in Get-ChildItem){UnzipFile -sourceFile $i.fullname -targetFolder "C:\Users\Documents\UiPath\2"}
附:查看PowerShell版本方法
- Win + R
- 输入Powershell,回车
- 输入 $host.Version.ToString(),回车
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)