I often have the following situation in my PowerShell code: I have a function or property that returns a collection of objects, or $null
. If you push the results in
If you can modify your function, have it return an empty collection/array instead of $null:
PS> function Empty { $null }
PS> Empty | %{'hi'}
hi
PS> function Empty { @() }
PS> Empty | %{'hi'}
Otherwise, go with what Oisin suggests although I would suggest a slight tweak:
filter Skip-Null { $_|?{ $_ -ne $null } }
Otherwise this will also filter 0
and $false
.
Update 4-30-2012: This issue is fixed in PowerShell v3. V3 will not iterate over a scalar $null value.