Powershell 使用ScriptBlock和ArgumentList调用时,Invoke命令仅返回单个对象

Powershell 使用ScriptBlock和ArgumentList调用时,Invoke命令仅返回单个对象,powershell,powershell-remoting,Powershell,Powershell Remoting,当使用-ScriptBlock、-ArgumentList和-Computer参数通过Invoke命令调用代码时,每次调用服务器只返回一个项目 下面可以找到两个突出问题的例子 $s = New-PSSession -ComputerName Machine01, Machine02 # when called, this block only retuns a single item from the script block # notice that the array variable

当使用
-ScriptBlock
-ArgumentList
-Computer
参数通过
Invoke命令
调用代码时,每次调用服务器只返回一个项目

下面可以找到两个突出问题的例子

$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

谁能解释一下我做错了什么?我不是唯一一个被这件事弄明白的人。

-ArgumentList
按照名字的意思,它将参数列表传递给命令。如果可能,该列表中的每个值都被指定给一个已定义的参数。但您只定义了一个参数:
$array
。因此,您只能从arg列表中获取第一个值

看,这实际上就是它的工作原理(3个参数绑定到3个参数):

所以,您实际上要做的是将一个数组作为一个参数传递

实现这一目标的一个方法是:

-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))
另一种方法(在这个简单的例子中)是使用
$args
变量:

Invoke-Command  -ScriptBlock {
    $args | % { $i = $_ ; Get-culture | select @{n = '__id'; e = {$i}}, DisplayName }
} -ArgumentList 1, 2, 3
谢谢。我以前在数组之前使用过“,”但已经完全忘记了它。仍然记不起它的名字。
Invoke-Command  -ScriptBlock {
    $args | % { $i = $_ ; Get-culture | select @{n = '__id'; e = {$i}}, DisplayName }
} -ArgumentList 1, 2, 3