首页 > 解决方案 > 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
    }
}

标签: powershellforeachzipextract

解决方案


你可以用更少的变量来做。当$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"

推荐阅读