Pipe complete array-objects instead of array items one at a time?

后端 未结 4 1059
北海茫月
北海茫月 2020-12-14 00:45

How do you send the output from one CmdLet to the next one in a pipeline as a complete array-object instead of the individual items in the array one at a time?

4条回答
  •  孤街浪徒
    2020-12-14 01:14

    Short answer: use unary array operator ,:

    ,$theArray | foreach{Write-Host $_}
    

    Long answer: there is one thing you should understand about @() operator: it always interpret its content as statement, even if content is just an expression. Consider this code:

    $a='A','B','C'
    $b=@($a;)
    $c=@($b;)
    

    I add explicit end of statement mark ; here, although PowerShell allows to omit it. $a is array of three elements. What result of $a; statement? $a is a collection, so collection should be enumerated and each individual item should be passed by pipeline. So result of $a; statement is three elements written to pipeline. @($a;) see that three elements, but not the original array, and create array from them, so $b is array of three elements. Same way $c is array of same three elements. So when you write @($collection) you create array, that copy elements of $collection, instead of array of single element.

提交回复
热议问题