PowerShell脚本参数作为数组传递

Sam*_*Sam 7 powershell

编辑:我已经将代码更改为一个简单的测试用例,而不是出现此问题的完整实现.

我试图从另一个脚本中调用一个Powershell脚本,但事情并没有像我期待的那样成功.据我所知,"&"运算符应该将数组扩展为不同的参数.那不是我的事.

caller.ps1

$scriptfile = ".\callee.ps1"
$scriptargs = @(
    "a",
    "b",
    "c"
)

& $scriptfile $scriptargs
Run Code Online (Sandbox Code Playgroud)

callee.ps1

Param (
    [string]$one,
    [string]$two,
    [string]$three
)

"Parameter one:   $one"
"Parameter two:   $two"
"Parameter three: $three"
Run Code Online (Sandbox Code Playgroud)

.\caller.ps1在以下输出中运行结果:

Parameter one:   a b c
Parameter two:
Parameter three:
Run Code Online (Sandbox Code Playgroud)

我认为我遇到的问题是 $scriptargs数组没有扩展,而是作为参数传递.我正在使用PowerShell 2.

如何让caller.ps1运行带有参数数组的callee.ps1?

Emp*_*LII 11

调用本机命令时,类似的调用& $program $programargs将正确地转义参数数组,以便可执行文件正确解析它.但是,对于PowerShell cmdlet,脚本或函数,没有需要进行序列化/解析往返的外部编程,因此数组作为单个值按原样传递.

相反,您可以使用splatting将数组(或哈希表)的元素传递给脚本:

& $scriptfile @scriptargs
Run Code Online (Sandbox Code Playgroud)

@& $scriptfile @scriptargs使中的值$scriptargs被施加到脚本的参数.

  • 请注意,splatting需要PowerShell 3.0或更高版本. (2认同)