将数组传递给脚本块中的指定参数之一



我试图找出一种方法来传递一个数组在一个单独的脚本命名参数。然而,我找不到任何解决办法。

Test2.ps1:

param(
    [int]$a,
    [int]$b,
    [int]$c,
    [string[]]$d
)
write-host "`$a = $a"
write-host "`$b = $b"
write-host "`$c = $c"
write-host "`$d:" -nonewline
foreach($str in $d) {
    write-host " $str" -nonewline
}
write-host
主脚本:

$arr = @("abc", "def", "ghi")
$params = @{
    a = 1;
    b = 2;
    c = 3;
    d = $arr
}
#invoke-command -filepath "test2.ps1" -ArgumentList 1,2,3,@("abc", "def", "ghi")
$scriptPath = "test2.ps1"
$sb = [scriptblock]::create(".{$(get-content $ScriptPath -Raw)} $(&{$args} @params)")
invoke-command -scriptblock $sb

当执行时,我得到的输出是

$d:System.Object[]

下面这行是从另一个Stackoverflow答案中复制的,但是我不太明白它是如何为前3个命名参数工作的。

$sb = [scriptblock]::create(".{$(get-content $ScriptPath -Raw)} $(&{$args} @params)")

特别是"$(&{$args} @params)"部分。我对飞溅有基本的了解,但这超出了我的能力。如果有人能给我解释一下语法,我将不胜感激。

当您将@params放入可扩展字符串中时,您将强制解析器将结果输出转换为字符串,并且ToString()的默认行为(如果未被覆盖)仅返回所讨论对象的类型名称。

只需等到调用脚本时再提供参数:

$sb = [scriptblock]::Create("$(get-content $ScriptPath -Raw)")
& $sb $args @params

或者,如果你想点源脚本与特定的参数:

$sb = [scriptblock]::Create("$(get-content $ScriptPath -Raw)")
& {.$sb $args @params}

最新更新