PowerShell调用7-Zip脚本字符串语法问题:参数未被正确识别
问题
尝试编写PowerShell脚本调用7z.exe执行压缩操作时遇到异常:直接用7z.exe语法在控制台能正常运行,但整合到脚本后失效。例如执行命令:
.\zip.ps1 "C:\test\test.zip" "C:\test\test1.txt" "C:\test\test2.txt*"
脚本并未按指定参数压缩目标文件,反而压缩了C:\test文件夹内的所有内容,同时出现以下错误警告:
Files read from disk: 0 Archive size: 22 bytes (1 KiB) Scan WARNINGS for files and folders: 1 : The system cannot find the file specified. ----------------
原脚本代码如下:
"Received $($args.Count) files:" $parent = Split-Path (Split-Path $args[0]) -Leaf $sevenzip = "C:\Program Files\7-Zip\7z.exe" $zipname = "$($parent) $(Get-Date -Format 'yyyy_MM_dd HH_mm_ss').zip" $args_line = $args | foreach-object { "`"$_`"" } # $args_line = '"' + $($args -join """" """" ) + '"' # Want to use """ here so that it can capture not only files with spaces, but files with ' in the filename '' "Zip Name : $zipname" '' "Arguments : $args_line" '' if (Test-Path $sevenzip) { if (Test-Path "C:\0\$zipname") { rm "C:\0\$zipname" -Force } '' 'String output of the line to run:' "& ""$sevenzip"" a -r -tzip ""C:\0\$zipname"" $args_line" # Taking this output and pasting onto console works. '' & "$sevenzip" a -r -tzip "C:\0\$zipname" "$args_line" # This does not work } else { "7z.exe was not found at '$sevenzip', please check and try again" }
问题根源
核心错误在于参数传递方式错误:
- 手动将每个参数包裹引号并拼接成字符串(
$args_line),最后调用7z时又将数组转成单个字符串("$args_line"),导致7z把整个拼接后的字符串当成一个路径参数,自然找不到对应文件。 - 加上
-r参数后,7z会递归扫描当前工作目录的所有内容,这就是误压缩整个C:\test文件夹的原因。
解决方法
PowerShell调用外部命令时,会自动处理带空格、特殊字符的路径,无需手动添加引号,直接传递参数数组即可:
修改后的脚本
"Received $($args.Count) files:" $parent = Split-Path (Split-Path $args[0]) -Leaf $sevenzip = "C:\Program Files\7-Zip\7z.exe" $zipname = "$($parent) $(Get-Date -Format 'yyyy_MM_dd HH_mm_ss').zip" $targetPath = "C:\0\$zipname" '' "Zip Name : $zipname" '' "Arguments : $($args -join ' ')" '' if (Test-Path $sevenzip) { # 先删除已存在的压缩包 if (Test-Path $targetPath) { Remove-Item $targetPath -Force } '' 'Executing command:' "& `"$sevenzip`" a -tzip `"$targetPath`" $($args -join ' ')" '' # 直接传递参数数组,无需手动拼接字符串 & $sevenzip a -tzip $targetPath $args } else { "7z.exe was not found at '$sevenzip', please check and try again" }
关键修改点
- 移除手动引号拼接:删除
$args_line的相关代码,直接使用原始的$args参数数组传递给7z。 - 修正7z调用语句:将
& "$sevenzip" a -r -tzip "C:\0\$zipname" "$args_line"改为& $sevenzip a -tzip $targetPath $args;若不需要递归扫描子目录,建议保留移除-r参数,避免误压缩无关文件。 - 优化变量命名:将
C:\0\$zipname存为$targetPath,提升代码可读性。
补充说明
如果需要支持通配符(比如test2.txt*),PowerShell会自动解析通配符并匹配对应文件,无需额外处理;若确实需要递归功能,再添加-r参数即可。
内容的提问来源于stack exchange,提问作者YorSubs
相关产品推荐
相关产品推荐

