【问题标题】:Invoke-Command returns only a single object when called using ScriptBlock and ArgumentList使用 ScriptBlock 和 ArgumentList 调用时,Invoke-Command 仅返回一个对象
【发布时间】:2019-03-21 21:52:42
【问题描述】:

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

可以在下面找到两个突出问题的示例。

$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

谁能向我解释我做错了什么?我不能是唯一一个被这个抓住的人。

【问题讨论】:

    标签: powershell powershell-remoting


    【解决方案1】:

    -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
    

    【讨论】:

    • 非常感谢。我以前在数组之前使用过“,”,但完全忘记了它。还是记不住它的名字。
    猜你喜欢
    • 1970-01-01
    • 2012-01-22
    • 1970-01-01
    • 2018-05-19
    • 2012-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多