在批处理文件中带参数运行脚本



我正在写一个批处理文件,在这个批处理文件中我执行一个脚本。

批处理文件:

PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""C:PublicFileSomeScript.ps1""' -Verb RunAs}"

现在可以正常工作了

是否可以执行SomeScript。带参数的Ps1 ?

@echo off
echo %1
echo %2
echo %3
echo %4
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""C:PublicFileSomeScript.ps1 Arg1 %1 Arg2 %2 Arg3 %3 Arg4 %4""' -Verb RunAs}"

批处理文件响应我给出的值。但在那之后什么都没有发生。所以我不确定我是否正确地传递了参数。

感谢任何帮助:)

  • 参数必须在引号外的脚本路径""C:PublicFileSomeScript.ps1""

  • 为了安全起见,你应该把参数也双引号。

  • 在调用Windows PowerShell(powershell.exe)的CLI时使用"来转义嵌入的双引号,而""用于PowerShell (Core)(pwsh.exe)。

    • 注意:由于cmd.exe的限制,在Windows PowerShell中使用"可能会中断,这取决于传递参数的具体值;丑陋的解决方法是使用"^""(sic)。

因此(为简洁起见,仅限于传递%1):

PowerShell -NoProfile -ExecutionPolicy Bypass -Command "Start-Process PowerShell '-NoProfile -ExecutionPolicy Bypass -File "C:PublicFileSomeScript.ps1" Arg1 "%1"' -Verb RunAs"

作为题外话:没有理由使用& { ... }来调用通过-Command(-c)参数传递给PowerShell CLI的代码-只需直接使用...,如上所示。旧版本的CLI文档错误地建议& { ... }是必需的,但这已经被纠正了。

最新更新