“Dangerous” Comparisons

by Feb 5, 2019

Let’s assume in an array you want to get rid of all elements that are either empty or null. This is what many would do:

 
PS> 1,2,$null,"test","",9 | Where-Object { $_ -ne '' -and $_ -ne $null }

1
2
test
9

PS>  
 

However, this comparison is dangerous because it also eliminates the value 0:

 
PS> 1,2,0,$null,"test","",0,9 | Where-Object { $_ -ne '' -and $_ -ne $null }

1
2
test
9

PS>  
 

PowerShell filters out the value 0 because it equals to an empty string:

 
PS> 0 -eq ''
True

PS> 1 -eq ''
False
 

This is because with comparisons, the data type of the left side counts, and since there is an integer on the left side, PowerShell converts the empty string to an integer as well, which happens to be the value 0.

In order to do a safe comparison, always make sure you place the relevant data type on the left side, not the right:

 
PS> 1,2,0,$null,"test","",0,9 | Where-Object { '' -ne $_ -and $null -ne $_ }

1
2
0
test
0
9

PS> 
 

Or better yet, use one of the API functions to identify empty values:

 
PS> 1,2,0,$null,"test","",0,9 | Where-Object { ![string]::IsNullOrWhiteSpace($_) }

1
2
0
test
0
9

PS>  
 

psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want to miss: PowerShell Conference EU – with 40 renown international speakers including PowerShell team members and MVPs, plus 350 professional and creative PowerShell scripters. Registration is open at www.psconf.eu, and the full 3-track 4-days agenda becomes available soon. Once a year it’s just a smart move to come together, update know-how, learn about security and mitigations, and bring home fresh ideas and authoritative guidance. We’d sure love to see and hear from you!

Twitter This Tip! ReTweet this Tip!