PowerShell - Strange implicit type conversion
PowerShell is great, but sometimes it has some strange quircks that can cost you a lot of time to solve. My latest "obstacle" was the following situation:
function ArgsToArrayList {
$al = new-object System.Collections.ArrayList
$args | foreach { [void] $al.add($_) }
$al
}
$x = ArgsToArrayList 1 2 3 4 5
write-Host "5 entries, type: " $x.GetType()
$x = ArgsToArrayList
write-Host "0 entries, is null: " ($x -eq $null)
I expect the function ArgsToArrayList to always return an object of type System.Collections.ArrayList, independent of the number of arguments passed. I was wrong.
PowerShell converts the return value of the function ArgsToArrayList from System.Collections.ArrayList to System.Object[] when it contains entries, and to $null when the arraylist is empty.
So the output of the above code is:
5 entries, type: System.Object[]
0 entries, is null: True
Beats me...