Passing Arrays to Pipeline

by May 7, 2015

If a function returns more than one value, PowerShell wraps them in an array. However, if you pass the results to another function inside a pipeline, the pipeline automatically "unwraps" the array and processes one array element at a time.

If you want to pass on a real array without unwrapping, make sure you wrap the return value in another array. This way, the pipeline unwraps the outer array and processes the inner array.

Here is a code to illustrate this:

#requires -Version 1


function Test-ArrayAsReturnValue1
{
  param($count)

  $array = 1..$count

  return $array
}

function Test-ArrayAsReturnValue2
{
  param($count)

  $array = 1..$count

  return ,$array
}

'Result 1:'
Test-ArrayAsReturnValue1 -count 10 | ForEach-Object -Process {
  $_.GetType().FullName 
}

'Result 2:'
Test-ArrayAsReturnValue2 -count 10 | ForEach-Object -Process {
  $_.GetType().FullName 
}

When you run this, the first example returns the elements of the produced array. The second call sends the entire array into the loop:

 
PS C:\> 

Result 1:
System.Int32
System.Int32
System.Int32
System.Int32
System.Int32
System.Int32
System.Int32
System.Int32
System.Int32
System.Int32

Result 2:
System.Object[] 

Twitter This Tip! ReTweet this Tip!