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

后端 未结 4 1047
北海茫月
北海茫月 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:06

    The comma character makes the data an array. In order to make the pipe line process your array as an array, instead of operating on each array element individually, you may also need to wrap the data with parentheses.

    This is useful if you need to assess the status of multiple items in the array.

    Using the following function

    function funTest {
        param (
            [parameter(Position=1, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
            [alias ("Target")]
            [array]$Targets 
            ) # end param
        begin {}
        process {
            $RandomSeed = $( 1..1000 | Get-Random )
            foreach ($Target in $Targets) {
                Write-Host "$RandomSeed - $Target"
                } # next target
            } # end process
        end {}
        } # end function 
    

    Consider the following examples:

    Just Wrapping your array in parentheses does not guarantee the function will process the array of values in one process call. In this example we see the random number changes for each element in the array.

    PS C:\> @(1,2,3,4,5) | funTest
    153 - 1
    87 - 2
    96 - 3
    96 - 4
    986 - 5
    

    Simply adding the leading comma, also does not guarantee the function will process the array of values in one process call. In this example we see the random number changes for each element in the array.

    PS C:\> , 1,2,3,4,5 | funTest
    1000 - 1
    84 - 2
    813 - 3
    156 - 4
    928 - 5
    

    With the leading comma and the array of values in parentheses, we can see the random number stays the same because the function's foreach command is being leveraged.

    PS C:\> , @( 1,2,3,4,5) | funTest
    883 - 1
    883 - 2
    883 - 3
    883 - 4
    883 - 5
    

提交回复
热议问题