代码之家  ›  专栏  ›  技术社区  ›  Chris Nelson

为什么我不能使用启动进程来调用带有参数的脚本?

  •  0
  • Chris Nelson  · 技术社区  · 5 年前

    我试图在Powershell中编写一个包装器脚本,它传递一个可执行文件的名称,进行一些预处理,然后使用预处理产生的参数调用该可执行文件。我希望可执行文件是任何你可以在Windows上运行/打开的文件,所以我想使用 Start-Process 如此运行 Invoke a second script with arguments from a script 其中引用了 Invoke-Expression

    我愚蠢的小测试是:

    Write-Output "Arg0: '$($Args[0])', Arg1: '$($Args[1])'" >>test.log
    

    在PS提示符下工作,我看到的是:

    PS C:\Source> .\test.ps1 a b
    PS C:\Source> more .\test.log
    Arg0: 'a', Arg1: 'b'
    
    PS C:\Source> .\test.ps1 c d
    PS C:\Source> more .\test.log
    Arg0: 'a', Arg1: 'b'
    Arg0: 'c', Arg1: 'd'
    
    PS C:\Source> Start-Process .\test.ps1 -ArgumentList e,f
    PS C:\Source> Start-Process .\test.ps1 -Args e,f
    PS C:\Source> more .\test.log                                                                                   
    Arg0: 'a', Arg1: 'b'
    Arg0: 'c', Arg1: 'd'
    Arg0: '', Arg1: ''
    Arg0: '', Arg1: ''
    
    PS C:\Source>   
    

    启动进程 在剧本里。我花了几个小时在谷歌上找不到答案。有什么想法吗?

    我正在开发Windows10,但我的目标是WindowsServer。我不知道那会有什么不同。

    0 回复  |  直到 5 年前
        1
  •  2
  •   codewario    5 年前

    您需要通过调用脚本 powershell.exe :

    Start-Process powershell -ArgumentList "-File .\test.ps1 arg1 arg2 argX"
    

    可以将参数列表指定为字符串或字符串数组。 See example 7 here 了解更多信息。

    如@mklement0在问题注释中所述,如果您不通过 父进程 ,它将在默认上下文中执行它,就像Windows认为的那样 .ps1 文件应该被执行,在这种情况下,它不会向脚本传递额外的参数。


    您可能不需要使用 Start-Process 不过,如果您不需要 启动进程 & 运算符,或指定脚本的路径,就像交互式地那样:

    # You can use a variable with the path to the script
    # in place of .\test.ps1 here and provide the arguments
    # as variables as well, which lets you build a dynamic
    # command out without using `Start-Process` or `Invoke-Expression`.
    & .\test.ps1 arg1 arg2 argX
    

    # You can use variables for the arguments here, but the script name
    # must be hardcoded. Good for cases where the entrypoint doesn't change.
    .\test.ps1 arg1 arg2 argX
    

    你也可以考虑使用 argument splatting 在构建动态命令时也可以使用。 I wrote an answer here 还有更详细的描述。

    推荐文章