Re: [请问] 以资料夹为名称针对资料夹内图片的批量压缩方法

楼主: falcon (falken)   2024-06-03 15:01:07
先安装 NanaZip 或 7-Zip
在 PowerShell 中输入 7z.exe 确认是否可用
若得到以下讯息则必须手动新增 7z.exe 所在目录到环境变量 PATH
"无法辨识 '7z.exe' 词汇是否为 Cmdlet、函数、指令档或可执行程式的名称。......"
在 PowerShell 中执行下列命令
使用前记得先修改 Path\To\Dir 为你要的主目录路径
Set-Location -LiteralPath 'Path\To\Dir'
$outputDirPath = $PWD.Path
foreach ($item in (Get-ChildItem -LiteralPath .)) {
$desFilePath = Join-Path $outputDirPath "$($item.Name).zip"
if ($item.PsIsContainer) {
$souFilePath = Join-Path $item.FullName *
} else {
$souFilePath = $item.FullName
}
& 7z.exe a "$($desFilePath)" "$($souFilePath)"
}
你也可只用 PowerShell 的 cmdlet 来达到相同功能
Set-Location -LiteralPath 'Path\To\Dir'
$outputDirPath = $PWD.Path
foreach ($item in (Get-ChildItem -LiteralPath .)) {
$desFilePath = Join-Path $outputDirPath "$($item.Name).zip"
$escDesFilePath = $desFilePath -replace '[\`\[\]]', '`$0'
if ($item.PsIsContainer) {
$escSouFileParentPath = $item.FullName -replace '[\`\[\]]', '`$0'
$escSouFilePath = Join-Path $escSouFileParentPath *
} else {
$escSouFilePath = $item.FullName -replace '[\`\[\]]', '`$0'
}
Compress-Archive -Path $escSouFilePath -DestinationPath $escDesFilePath
}
以下是补充说明
- 路径中单独的 . 等同 $PWD.Path
- Get-ChildItem 'path\to\dir' 等同 Get-Item 'path\to\dir\*'
- 用参数 -LiteralPath 指定输入,则不会将路径中的任何字符视为特殊字符
- 若只是要在路径中使用 * 字符,则可用 -replace 跳脱路径中的方括号字符
- 工作目录中带有特殊字符可能会导致某些 cmdlet 找不到相对路径的目标,所以喂给 cmdle
t 的路径最好是绝对路径。
例如把 .\file.ext 转成绝对路径的方法如下
$ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath('.\file.ext')
大概就这样…
作者: sanbis (方正無法達成,那麼有沒H)   2024-06-05 20:22:00
感激~ f 大提供的程式~晚点来测试一下 m(_ _)m
作者: sank (SANKK)   2024-06-22 21:25:00

Links booklink

Contact Us: admin [ a t ] ucptt.com