【问题标题】:Run Script within Batch File with Parameters使用参数在批处理文件中运行脚本
【发布时间】:2021-11-16 00:33:39
【问题描述】:

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

批处理文件:

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}"

批处理文件与我提供的值相呼应。但在那之后什么也没有发生。所以我不确定我是否正确传递了参数。

任何帮助表示赞赏:)

【问题讨论】:

    标签: powershell batch-file parameters arguments script


    【解决方案1】:
    • 参数必须在外部引用的脚本路径""C:\Public\File\SomeScript.ps1""

    • 为了安全起见,您也应该双引号。

    • 在调用 Windows PowerShell 的 CLI 时使用 \" 转义嵌入的双引号(powershell.exe),如您的情况),"" 用于 PowerShell(核心) (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 错误地建议 & { ... } 是必需的,但这已经得到纠正。

    【讨论】:

    • 嗨 mklement0,我不是 Powershell 用户,但我确实阅读了带有 batch-file 标记的用户。我不时看到执行 Powershell 的双重用途。这样做的目的是什么?
    • @Squashman,为了创建一个 elevated 进程是必要的,这不能直接完成:第一个powershell 调用调用Start-Process -Verb RunAs,它创建了一个提升的(以管理员身份运行)进程。在这种情况下,它是另一个 PowerShell 进程,但您可以使用该技术启动任何具有提升的程序。
    猜你喜欢
    • 2015-07-06
    • 2015-01-03
    • 2018-02-01
    • 1970-01-01
    • 2014-05-04
    • 2011-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多