我正在尝试在 Powershell 中编写一个包装器脚本,该脚本传递可执行文件的名称,进行一些预处理,然后使用该预处理产生的参数调用该可执行文件。我希望可执行文件是可以在 Windows 上运行/打开的任何内容,所以我想使用Start-Process
运行它使用脚本中的参数调用第二个脚本(其中引用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 Server。我不知道这会有所作为。
您需要通过调用脚本powershell.exe
:
Start-Process powershell -ArgumentList "-File .\test.ps1 arg1 arg2 argX"
您可以将参数列表指定为字符串或字符串数组。请参阅此处的示例 7了解更多信息。
正如@mklement0在问题评论中所述,如果您不通过调用它powershell.exe
,它将在 Windows 认为的默认上下文中执行它.ps1
文件应该被执行,在这种情况下不会将额外的参数传递给脚本。
您可能不需要使用Start-Process
不过 - 如果您不需要提供的任何特殊功能Start-Process
您也可以使用 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
or
# 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
您可能还想考虑使用论据分散在构建动态命令时也可以用于您的论点。我在这里写了一个答案以及更详细地介绍了泼溅。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)