views:

316

answers:

2

I am trying to return List< T> from PowerShell function, but get one of:

  1. null - for empty list
  2. System.Int32 - for list with one element
  3. System.Object[] - for list with more elements

Code:

function CreateClrList
{
    $list = New-Object "System.Collections.Generic.List``1[System.Int32]"
    $list.Add(3)
    $list
}

Write-Host (CreateClrList).GetType()
+6  A: 

Yeah, powershell unrolls all collections. One solution is to return a collection containing the real collection, using the unary comma:

function CreateClrList
{
    $list = New-Object "System.Collections.Generic.List``1[System.Int32]"
    $list.Add(3)
    ,$list
}
jachymko
Nooooooooooooooooooo! But thanks for the workaround
Peter Seale
A: 

Note that most of the time, you want Powershell to unroll enumerable types so that piped commands execute faster and with earlier user feedback, since commands down the pipe can start processing the first items and give output.

Ludovic