【问题标题】:PowerShell extract each zip file to own folderPowerShell 将每个 zip 文件解压缩到自己的文件夹
【发布时间】:2021-12-07 05:23:57
【问题描述】:

我想将一些文件分别解压缩到与 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
    }
}

【问题讨论】:

  • 它看起来相当不错,所以如果它工作正常,则无需寻找替代解决方案。当然,总有可用的替代解决方案,但如果运行良好,则无需修改。您可以使用的一件事是拆分路径以摆脱扩展
  • 你可以从$i.BaseName得到$name_noext,但除此之外,当前的实现有什么问题?为什么减少代码行很重要?
  • 我经常发现我以简单的方式做上述事情,但后来我看到一些智能的面向对象的方式简化了我笨重的方法 - 实际上它是关于更好的方式/技巧当我对多个文件执行此类操作时,PowerShell 更智能且通常有用,因为我经常执行上述操作。

标签: powershell foreach zip extract


【解决方案1】:

您可以减少一些变量。当 $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"

【讨论】:

  • 这很好,这里有一些非常有趣的观点,谢谢。使用$null = 只是为了抑制输出吗?这是否与这些行末尾的 | Out-Null 相同,还是在 PowerShell 中使用 $null = 更好的构造?
  • @YorSubs 是的,这是正确的。我个人更喜欢$null =,因为通过使用它,我们不会通过管道发送任何东西,因此它也比| Out-Null 快一点。
猜你喜欢
  • 1970-01-01
  • 2013-12-25
  • 1970-01-01
  • 1970-01-01
  • 2021-05-16
  • 2018-10-21
  • 2015-04-05
  • 2020-05-02
  • 2021-10-16
相关资源
最近更新 更多