PowerShell 5.1嵌套Start-Process传参时连续空格被合并问题
PowerShell嵌套命令路径连续空格丢失问题解决方案
问题原因
你遇到的问题由两个核心因素共同导致:
- PowerShell 5.1的
Start-Process在传递字符串类型的-ArgumentList参数时,会自动对输入字符串做命令行解析,默认合并连续空格 - 多层嵌套的命令需要同时处理外层PowerShell解析、内层PowerShell解析、wscript参数解析三层规则,转义序列很容易在某一层被提前解析,导致最终传递的参数格式错误
可行解决方案
推荐使用Base64编码传递命令的方案,完全规避转义冲突和空格合并问题,完美适配路径带连续空格、特殊字符、需要变量展开的场景:
# 原有凭据创建逻辑无需修改 $username = 'Username' $password = 'Password' $securePassword = ConvertTo-SecureString $password -AsPlainText -Force $credential = New-Object System.Management.Automation.PSCredential $username, $securePassword # 构造内层要执行的命令,变量直接正常展开,不需要额外转义 $innerCommand = @" Start-Process -FilePath wscript.exe -Verb RunAs -ArgumentList "`"$PWD\test.vbs`" `" /CurrentDirectory:$PWD`" `" /AppData:$env:APPDATA`"" "@ # 将命令转为UTF-16LE编码的Base64字符串,适配PowerShell内置的-EncodedCommand参数 $commandBytes = [System.Text.Encoding]::Unicode.GetBytes($innerCommand) $encodedCommand = [Convert]::ToBase64String($commandBytes) # 外层调用直接传递编码后的命令,无任何转义冲突 Start-Process -FilePath powershell.exe ` -WorkingDirectory "$env:ALLUSERSPROFILE" ` -Credential $credential ` -WindowStyle Hidden ` -ArgumentList "-NoProfile -EncodedCommand $encodedCommand"
方案优势
- 完全保留路径中的连续空格、单引号、双引号等所有特殊字符,不会被篡改
- 变量可以正常展开,不需要处理单引号包裹无法展开变量的问题
- 兼容所有PowerShell 5.1版本,无额外依赖
- 后续如果需要调整内层命令逻辑,只需要修改
$innerCommand部分即可,外层调用无需调整
内容的提问来源于stack exchange,提问作者Mario Palumbo
相关产品推荐
相关产品推荐

