使用ScriptBlock和ArgumentList调用时,Invoke-Command仅返回单个对象

问题描述 投票:1回答:1

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

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

-ScriptBlock

任何人都可以向我解释我做错了什么吗?我不能成为唯一被这个人抓住的人。

powershell powershell-remoting
1个回答
0
投票

-ArgumentList执行名称所暗示的内容,它将命令的参数列表传递给它。如果可能,该列表中的每个值都将分配给已定义的参数。但是你只定义了一个参数:-Computer。因此,您只能从arg列表中获取第一个值。

看,这实际上是它应该如何工作(3个参数绑定到3个参数):

$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

另一种方式(在这个简单的情况下)将使用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 -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))
© www.soinside.com 2019 - 2024. All rights reserved.