Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell function won't return object

I have a simple function that creates a generic List:

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?

like image 537
Dan Avatar asked Dec 22 '22 02:12

Dan


1 Answers

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:

,[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:

function test {
 param($myParameter, $myParameter2)
}

or

function  {
param(
  [Parameter(Mandatory=true, Position=0)]$myParameter,
  ... again $myParameter2)
...
like image 169
stej Avatar answered Jan 18 '23 11:01

stej