为什么我不能使用 Start-Process 来调用带参数的脚本?

Why can't I use Start-Process to invoke a script with parameters?

我正在尝试在 Powershell 中编写一个包装器脚本,该脚本传递一个可执行文件的名称,进行一些预处理,然后使用该预处理产生的参数调用该可执行文件。我希望可执行文件是任何你可以 run/open 在 Windows 上的东西所以我想使用 Start-Process 到 运行 所以 Invoke a second script with arguments from a script (引用 Invoke-Expression) 并不真正相关。我发现当可执行文件是另一个 Powershell 脚本时,脚本看不到参数。

我愚蠢的小测试是:

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>   

这与我在脚本中使用 Start-Process 时看到的一致。我花了几个小时谷歌搜索却没有找到答案。有什么想法吗?

我正在 Windows 10 进行开发,但我的目标是 Windows 服务器。我不知道这应该有所作为。

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

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

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

如@mklement0 在问题评论中所述,如果您不通过 powershell.exe 调用它,它将在默认上下文中执行它,因为 Windows 认为 .ps1应该执行文件,在这种情况下不会将其他参数传递给脚本。


虽然您可能不需要使用 Start-Process - 如果您不需要 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 for your arguments as well when building out dynamic commands. I wrote an answer here 以及更详细的 splatting。