PowerShell Gotchas: Looping with $null


For some obscene reason, PSHv1 will gladly iterate with a $null as an array element in Foreach.


@($null, 1, $null, 2) | Foreach { “‘$_'”; }



‘1’

‘2’


So, in the name of defensive programming, I’ve taken to manually testing for this case:


@($null, 1, $null, 2) | Foreach { if ($_) { “‘$_'”; } }


‘1’
‘2’


 

Comments (0)