运行 带参数的批处理文件中的脚本
Run Script within Batch File with Parameters
我正在编写一个批处理文件,并在这个批处理文件中执行一个脚本。
批处理文件:
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""C:\Public\File\SomeScript.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:\Public\File\SomeScript.ps1 Arg1 %1 Arg2 %2 Arg3 %3 Arg4 %4""' -Verb RunAs}"
批处理文件与我提供的值相呼应。但在那之后什么也没有发生。所以我不确定我是否正确传递了参数。
感谢任何帮助:)
参数必须在引用的脚本路径之外,""C:\Public\File\SomeScript.ps1""
为了安全起见,您也应该将参数双引号。
在调用 Windows PowerShell (powershell.exe
) 的 CLI 时使用 \"
转义嵌入的双引号作为在你的情况下)和 ""
对于 PowerShell (Core) (pwsh.exe
).
- 注意:根据传递参数的具体值,由于
cmd.exe
的限制,将 \"
与 Windows PowerShell 一起使用可能会中断; -丑陋的解决方法是使用"^""
(原文如此)。
因此(为简洁起见仅限于通过 %1
):
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "Start-Process PowerShell '-NoProfile -ExecutionPolicy Bypass -File \"C:\Public\File\SomeScript.ps1\" Arg1 \"%1\"' -Verb RunAs"
顺便说一句:没有理由使用 & { ... }
来调用通过 -Command
(-c
) 参数传递给 PowerShell CLI 的代码 - 只需使用 ...
直接,如上图。 CLI documentation 的旧版本错误地建议 & { ... }
是必需的,但这已被更正。
我正在编写一个批处理文件,并在这个批处理文件中执行一个脚本。
批处理文件:
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""C:\Public\File\SomeScript.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:\Public\File\SomeScript.ps1 Arg1 %1 Arg2 %2 Arg3 %3 Arg4 %4""' -Verb RunAs}"
批处理文件与我提供的值相呼应。但在那之后什么也没有发生。所以我不确定我是否正确传递了参数。
感谢任何帮助:)
参数必须在引用的脚本路径之外,
""C:\Public\File\SomeScript.ps1""
为了安全起见,您也应该将参数双引号。
在调用 Windows PowerShell (
powershell.exe
) 的 CLI 时使用\"
转义嵌入的双引号作为在你的情况下)和""
对于 PowerShell (Core) (pwsh.exe
).- 注意:根据传递参数的具体值,由于
cmd.exe
的限制,将\"
与 Windows PowerShell 一起使用可能会中断; -丑陋的解决方法是使用"^""
(原文如此)。
- 注意:根据传递参数的具体值,由于
因此(为简洁起见仅限于通过 %1
):
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "Start-Process PowerShell '-NoProfile -ExecutionPolicy Bypass -File \"C:\Public\File\SomeScript.ps1\" Arg1 \"%1\"' -Verb RunAs"
顺便说一句:没有理由使用 & { ... }
来调用通过 -Command
(-c
) 参数传递给 PowerShell CLI 的代码 - 只需使用 ...
直接,如上图。 CLI documentation 的旧版本错误地建议 & { ... }
是必需的,但这已被更正。