当使用Invoke-Command
,-ScriptBlock
和-ArgumentList
参数通过-Computer
调用代码时,每次调用仅返回单个项到服务器。
在突出显示问题的下方可以找到两个示例。
$s = New-PSSession -ComputerName Machine01, Machine02
# when called, this block only retuns a single item from the script block
# notice that the array variable is being used
Invoke-Command -Session $s -ScriptBlock {
param( $array )
$array | % { $i = $_ ; Get-culture | select @{name='__id'; ex={$i} } , DisplayName
}
} -ArgumentList 1,2,3
write-host "`r`n======================================`r`n"
# when called, this block retuns all items from the script block
# notice that the call is the same but instead of using the array variable we use a local array
Invoke-Command -Session $s -ScriptBlock {
param( $array )
1,2,3 | % { $i = $_ ; Get-culture | select @{name='__id'; ex={$i} } , DisplayName
}
} -ArgumentList 1,2,3
$s | Remove-PSSession
有人可以向我解释我在做什么错吗?我不能成为唯一被这个迷住的人。
答案 0 :(得分:0)
-ArgumentList
顾名思义,将参数列表传递给命令。如果可能,该列表中的每个值都分配给已定义的参数。但是您只定义了一个参数:$array
。因此,您只能从arg列表中获取第一个值。
看,这实际上是应该如何工作的(3个参数绑定到3个参数):
Invoke-Command -Session $s -ScriptBlock {
param ($p1, $p2, $p3)
$p1, $p2, $p3 | % { $i = $_ ; Get-culture | select @{name='__id'; ex={$i} } , DisplayName }
} -ArgumentList 1, 2, 3
因此,您实际要做的是将 one 数组作为 one 单个参数传递。
一种实现该目标的方法是:
-ArgumentList (,(1, 2, 3))
最终代码:
Invoke-Command -Session $s -ScriptBlock {
param ($array)
$array | % { $i = $_ ; Get-culture | select @{n = '__id'; e = {$i}}, DisplayName }
} -ArgumentList (, (1, 2, 3))
另一种方式(在这种简单情况下)将使用automatic $args
变量:
Invoke-Command -ScriptBlock {
$args | % { $i = $_ ; Get-culture | select @{n = '__id'; e = {$i}}, DisplayName }
} -ArgumentList 1, 2, 3