Powershell:如何管道数组本身而不是其项

时间:2018-11-01 10:21:21

标签: powershell

如何编写从数组(实际上是任何对象)获取数组作为对象的函数而又不迭代其项和另一个参数(位置)的函数。目标是修改容器(数组),而不修改其项目。像这样:

function xxx {
  Param( magic-specification??? )
  if ($obj type is array) {
    iterate over $obj items {
      $res = executes $args[0] script-block over them ($_)
      if ($res) modify $obj
    }
  else if ($obj type is object) {
    iterate over $obj properties {
      $res = executes $args[0] script-block over them ($_)
      if ($res) modify $obj property
    }
  }

1 个答案:

答案 0 :(得分:2)

这是一个演示示例,说明如何绕过PoSh的意图 来展开通过管道发送的项目...

,@(1,2,3) | ForEach-Object {$_.GetType(); "$_" } | Out-Host
@(1,2,3) | ForEach-Object {$_.GetType(); "$_" } | Out-Host
1,2,3 | ForEach-Object {$_.GetType(); "$_" } | Out-Host

输出...

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array
1 2 3


IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Int32                                    System.ValueType
1
True     True     Int32                                    System.ValueType
2
True     True     Int32                                    System.ValueType
3


IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Int32                                    System.ValueType
1
True     True     Int32                                    System.ValueType
2
True     True     Int32                                    System.ValueType
3

请注意,第一个已通过数组,而其他所有都已展开该数组。前导,是数组运算符,它使PoSh发送包裹在另一个数组中的数组。外部的一个展开,内部的一个作为数组传递。