Powershell 为什么可以';我是否使用启动进程调用带有参数的脚本?

Powershell 为什么可以';我是否使用启动进程调用带有参数的脚本?,powershell,parameters,start-process,Powershell,Parameters,Start Process,我正在尝试在Powershell中编写一个包装器脚本,它被传递一个可执行文件的名称,进行一些预处理,然后使用预处理产生的参数调用该可执行文件。我希望可执行文件是您可以在Windows上运行/打开的任何文件,因此我希望使用启动进程来运行它,这样(引用调用表达式)就不太相关了。我发现,当可执行文件是另一个Powershell脚本时,脚本看不到参数 我愚蠢的小测试是: Write-Output "Arg0: '$($Args[0])', Arg1: '$($Args[1])'" >>tes

我正在尝试在Powershell中编写一个包装器脚本,它被传递一个可执行文件的名称,进行一些预处理,然后使用预处理产生的参数调用该可执行文件。我希望可执行文件是您可以在Windows上运行/打开的任何文件,因此我希望使用
启动进程
来运行它,这样(引用
调用表达式
)就不太相关了。我发现,当可执行文件是另一个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
时看到的一致。我花了几个小时在谷歌上搜索,没有找到答案。有什么想法吗


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

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

Start-Process powershell -ArgumentList "-File .\test.ps1 arg1 arg2 argX"
可以将参数列表指定为字符串或字符串数组。了解更多信息

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


但是,您可能不需要使用
启动流程
——如果您不需要
启动流程
提供的任何特殊功能,您也可以使用call
操作符调用脚本,或者通过指定脚本的路径,就像以交互方式一样:

# 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



在构建动态命令时,您可能还需要研究参数的使用。还有更详细的splatting。您需要通过
powershell.exe调用脚本:

Start-Process powershell -ArgumentList "-File .\test.ps1 arg1 arg2 argX"
可以将参数列表指定为字符串或字符串数组。了解更多信息

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


但是,您可能不需要使用
启动流程
——如果您不需要
启动流程
提供的任何特殊功能,您也可以使用call
操作符调用脚本,或者通过指定脚本的路径,就像以交互方式一样:

# 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



在构建动态命令时,您可能还需要研究参数的使用。以及更详细的splatting操作。

启动过程。\test.ps1
\test.ps1
视为文档,它执行与在资源管理器中双击文件(默认情况下,打开脚本进行编辑)相同的默认操作。另外,默认情况下,
启动进程
是异步的,因此您必须通过
-Wait
。如果只想在同一控制台窗口中同步运行脚本/控制台应用程序,则根本不要使用
启动进程
启动进程。\test.ps1
\test.ps1
视为文档,它执行与在资源管理器中双击文件时相同的默认操作(默认情况下,打开脚本进行编辑)。另外,默认情况下,
启动进程
是异步的,因此您必须通过
-Wait
。如果您只是想在同一控制台窗口中同步运行脚本/控制台应用程序,请不要使用
启动进程
。谢谢。
和$executable@argsArray
,然后测试
$?
可以满足我的要求。谢谢.
和$executable@argsArray
然后测试
$?
实现了我想要的。