I am trying to return List< T> from PowerShell function, but get one of:
If you need to return a list of ints, use jachymko's solution.
Otherwise, if you do not particularly care whether what you get is a list or array, but just want to iterate through result, you can wrap result in @() while enumerating, e.g.
$fooList = CreateClrList
foreach ($foo in @($fooList))
{
...
}
That would cause @($fooList)
to be of array type - either an empty array, array with one element or array with multiple elements.
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.
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
}
PowerShell 5.0 added support for classes and hence methods where the return type can be specified. To control the type returned, use a class with a static method:
class ListManager {
static [System.Collections.Generic.List[int]] Create() {
[System.Collections.Generic.List[int]] $list =
[System.Collections.Generic.List[int]]::new()
$list.Add(3)
return $list
}
}
[ListManager]::Create().GetType()