4

我有一个internal.ps1接受某些参数的脚本:

param ($paramA, $paramB)
Write-Host $PSBoundParameters

以及一个调用它的脚本caller.ps1

.\internal -paramA A -paramB B

它工作得很好:

PS C:\temp> .\caller
[paramA, A] [paramB, B]    <<<< bounded to both params

但是,在调用者中,我想将参数保留在 var 中,并在以后使用。但是,这不起作用:

$parms = "-paramA A -paramB B"
# Later...
.\internal $parms

Result: [paramA, A -paramB B]   <<<<< All got bounded to ParamA

也不使用数组:

$parms = @("A", "B")
# Later...
.\internal $parms

Result: [paramA, System.Object[]]  <<<< Again, all bound to ParamA

我怎样才能做到这一点?请注意,实际的命令行更复杂,并且可能有未知的长度。

4

3 回答 3

5

喷溅运算符(@) 应该可以满足您的需要。首先考虑这个简单的函数:

function foo($a, $b) { "===> $a + $b" }

使用显式参数调用会产生您所期望的结果:

foo "hello" "world"
===> hello + world

现在将这两个值放入一个数组中;正如您所观察到的,传递正常数组会产生不正确的结果:

$myParams = "hello", "world"
foo $myParams
===> hello world +

但是 splat 数组,你会得到想要的结果:

foo @myParams
===> hello + world

这适用于脚本和函数。回到你的脚本,结果如​​下:

 .\internal @myParams
[paramA, hello] [paramB, world]

最后,这将适用于任意数量的参数,因此需要了解它们的先验知识。

于 2013-06-19T18:00:22.740 回答
0

powershell -file c:\temp\test.ps1 @("A","B")

或者

powershell -command "c:\temp\test.ps1" A,B

于 2013-06-19T11:13:34.527 回答
0

您的脚本需要 2 个参数,但您之前的尝试只传递一个(分别是字符串和数组)。像这样做:

$parms = "A", "B"
#...
.\internal.ps1 $parm[0] $parm[1]
于 2013-06-19T12:09:05.537 回答