PowerShell function won’t return object


I have a simple function that creates a generic List:

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.



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:

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:

Note: you dont need to declare the function header with parenthesis. If you need to add parameters, the function will look like this:



PowerShell function won’t return object by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply