Techno Fattie

Josh Carroll

PowerShell is awesome! However, it also has its share of maddening quirks.

Jim Christopher (@beefarino) has highlighted one such quirk in the form of a brain teaser on his blog. The question is deceptively simple, but unless you have done a dance or three with PowerShell it might leave you scratching your head.

Query: In PowerShell, when is the following statement true? Explain why.
     ( $a -eq $b ) -ne ( $b -eq $a )

Know the answer? Try assigning these values to $a and $b

$a = 1
$b = '01'

If you run that expression again, it should come up as true.


It all has to do with what PowerShell is doing automatically for you. Since a string and an integer are disparate types, PowerShell is attempting to cast the values to the same type in order to do a comparison. In order to determine which type to cast to, the left operand is used.

If we write our expression out the way it is being interpreted, then it becomes pretty obvious what is going on.

([int]1 -eq [int]'01') -ne ([string]'01' -eq [string]1)

See what's going on? Obviously casting '01' to an [int] is not the same as casting 1 to a [string].

This is one of those things that makes sense when you look at it directly, but when it is an obscure bug buried deep inside one of your production scripts... it can drive you insane.

Just remember that equality comparisons in PowerShell are not always commutative.

Happy Scripting, and thanks @beefarino for a fun challenge, and being the guy who made me want to learn PowerShell in the first place :)
comments powered by Disqus