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版本方法

  1. Win + R
  2. 输入Powershell,回车
  3. 输入 $host.Version.ToString(),回车
    在这里插入图片描述
  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值