如何通过 powershell Start-Process 将引用的参数传递给提升的批处理脚本

How to pass quoted arguments to elevated batch script via powershell Start-Process

我很难在提升时将引号传递给 .bat 文件,二进制文件似乎可以工作……重现步骤:

创建一个小的测试批处理脚本%TEMP%\test.bat包含

echo.%* && pause

启动 powershell 并尝试这些:

# both behave like expected, echoing hello and pausing
saps -filepath cmd -argumentlist '/c echo.hello && pause'
saps -filepath "$env:TEMP\test.bat" -argumentlist 'hello'

# both behave like expected, echoing "hello" and pausing
saps -filepath cmd -argumentlist '/c echo."hello" && pause'
saps -filepath "$env:TEMP\test.bat" -argumentlist '"hello"'

# both behave like expected, echoing an elevated hello and pausing
saps -verb runas -filepath cmd -argumentlist '/c echo.hello && pause'
saps -verb runas -filepath "$env:TEMP\test.bat" -argumentlist 'hello'

# cmd still echoes correctly "hell"no and pauses
saps -verb runas -filepath cmd -argumentlist '/c echo."hell"no && pause'

# tl;dr

# now this is where hell breaks loose
saps -verb runas -filepath "$env:TEMP\test.bat" -argumentlist '"hell"no'
# doesnt echo anything, window pops up and vanishes in an instant
# doesnt pause

如果直接在批处理文件上调用 "runas" 动词,则它不起作用。您需要在实际的可执行文件(即 cmd.exe)上调用它,并将批处理文件作为参数传递。

$params = '/c', "$env:TEMP\test.bat", '"hell"no'
Start-Process -Verb Runas -FilePath $env:ComSpec -ArgumentList $params