powershell - PowerShell 将每个 zip 文件解压缩到自己的文件夹
问题描述
我想将一些文件解压缩到与 zip 文件同名的文件夹中。我一直在做类似这样的笨拙的事情,但由于这是 PowerShell,通常有一种更聪明的方法来实现事情。
是否有某种一两行方法可以对文件夹中的每个 zip 文件进行操作并将其解压缩到与 zip 同名的子文件夹中(但没有扩展名)?
foreach ($i in $zipfiles) {
$src = $i.FullName
$name = $i.Name
$ext = $i.Extension
$name_noext = ($name -split $ext)[0]
$out = Split-Path $src
$dst = Join-Path $out $name_noext
$info += "`n`n$name`n==========`n"
if (!(Test-Path $dst)) {
New-Item -Type Directory $dst -EA Silent | Out-Null
Expand-Archive -LiteralPath $src -DestinationPath $dst -EA Silent | Out-Null
}
}
解决方案
你可以用更少的变量来做。当$zipfiles
集合包含 FileInfo 对象时,可以使用对象已有的属性替换大多数变量。
另外,尽量避免与变量连接,+=
因为这既耗时又耗内存。
只需将您在循环中输出的任何结果捕获到变量中即可。
像这样的东西:
# capture the stuff you want here as array
$info = foreach ($zip in $zipfiles) {
# output whatever you need to be collected in $info
$zip.Name
# construct the folderpath for the unzipped files
$dst = Join-Path -Path $zip.DirectoryName -ChildPath $zip.BaseName
if (!(Test-Path $dst -PathType Container)) {
$null = New-Item -ItemType Directory $dst -ErrorAction SilentlyContinue
$null = Expand-Archive -LiteralPath $zip.FullName -DestinationPath $dst -ErrorAction SilentlyContinue
}
}
# now you can create a multiline string from the $info array
$result = $info -join "`r`n==========`r`n"
推荐阅读
- javascript - 如何随着形状的旋转和位置的变化移动点
- r - 如何将重复出现的长对数据集转换为矩阵频率表
- java - Java AWS Lambda 处理程序 - 深度嵌套的 Json
- c# - 没有常量类型参数的理论测试迭代不会在测试资源管理器中显示为单独的迭代
- docker - 私有注册表的 Docker 拉取限制
- c++ - 为什么在我的“readSQL”方法中的“getVector”期间会出现 OCI-30757?
- javascript - 如何将方法对象添加到数组对象中以在项目中使用
- unit-testing - 启用两因素身份验证时的 ASP.Net Core XUnit 集成测试
- python - 写入后文本文件不显示
- android - 无法使用片段中的工具栏膨胀选项菜单