我想將一些檔案解壓縮到與 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
}
}
uj5u.com熱心網友回復:
你可以用更少的變數來做。當$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"
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/331901.html
