Powershell Functions do not return single element arrays

less than 1 minute read

I came across an interesting problem today that a function I wrote to return all SCCM primary sites worked at work but did not work at home. the difference between 2 SCCM environments is that I only have 1 single SCCM site in my home environment comparing to large multi-tier SCCM infrastructure at work. after some investigation I found out this common issue with Powershell when comes to returning arrays from a function.

For example:

image

The first function foo should returns a single element arraylist, and the variable it returned has the same type as the type of the only element in the arraylist.

The second function boo should returns a two-element arraylist but the type of returned variable has changed from .NET arraylist to normal powershell array.

So how should I get Powershell to return the same variable type in a function when it’s some sort of array?

In the return statement inside of the function, add a comma (",") in front of variable:

.NET ArrayList:

image

 

Normal Powershell arrays:

image

More readings about this here and here

Leave a comment