This is a really silly quick trick, but it can drive more than one developer crazy if they aren’t used to PowerShell’s quirks. Taking this code as an example:

function Get-EmptyArray {
 [System.Collections.ArrayList]$anyArray = @()
 return $anyArray
}

Write-Host (Get-EmptyArray).GetType()

At first it might seem pretty obvious that running it will print the string “System.Collections.Arraylist”. Well, no. The result will be a massive error along the lines of “You cannot call a method on a null-valued expression”.

The explanation for this behavior has to do with the way PowerShell manages what a function returns, and I think it’s worth another mini post. Since the goal here is knowing the fix, the trick is simple:

function Get-EmptyArray {
 [System.Collections.ArrayList]$anyArray = @()
 return ,$anyArray
}

Write-Host (Get-EmptyArray).GetType()

In case the difference isn’t easy to spot, the trick is putting a comma in front of the $anyArray variable in the return. Easy, simple and ugly, but it works 😉