Question:
I have a simple function that creates a generic List:
1 2 3 4 5 6 7 8 9 10 |
function test() { $genericType = [Type] "System.Collections.Generic.List``1" [type[]] $typedParameters = ,"System.String" $closedType = $genericType.MakeGenericType($typedParameters) [Activator]::CreateInstance($closedType) } $a = test |
The problem is that $a
is always null no matter what I try. If I execute the same code outside of the function it works properly.
Thoughts?
Answer:
IMHO that’s pitfall #1. If you return an object from the function that is somehow enumerable (I don’t know exactly if implementing IEnumerable
is the only case), PowerShell unrolls the object and returns the items in that.
Your newly created list was empty, so nothing was returned. To make it work just use this:
1 2 |
,[Activator]::CreateInstance($closedType) |
That will make an one item array that gets unrolled and the item (the generic list) is assigned to $a
.
Further info
Here is list of similar question that will help you to understand what’s going on:
- Powershell pitfalls
- Avoiding Agnostic Jagged Array Flattening in Powershell
- Strange behavior in PowerShell function returning DataSet/DataTable
- What determines whether the Powershell pipeline will unroll a collection?
Note: you dont need to declare the function header with parenthesis. If you need to add parameters, the function will look like this:
1 2 3 4 |
function test { param($myParameter, $myParameter2) } |
or
1 2 3 4 5 6 |
function { param( [Parameter(Mandatory=true, Position=0)]$myParameter, ... again $myParameter2) ... |