Common Pitfall and Strange Results: Comparison Operator

by Apr 21, 2023

Can you spot what’s wrong in the code below?

$result = 'NO'

if ($result = 'YES')
{
    'Result: YES'
}
else
{
    'Result: NO'
}

It always returns “Result: YES”, regardless of whether $result contains “NO” or “YES”.

People transitioning from other script or programming languages to PowerShell often run into this error: in PowerShell, “=” is an exclusive assignment operator, and for comparison you need to use “-eq” instead. So, the correct code (and simple fix) would be this:

$result = 'NO'

if ($result -eq 'YES')
{
    'Result: YES'
}
else
{
    'Result: NO'
}

Let’s take a look at why the initial code was always returning “Result: YES” in the first place.

When you accidentally use the assignment operator instead of a comparison operator, you do not get any result, so this NULL value should really evaluate to $false, and the condition should always return “Result: NO”. However, the opposite is the case.

This is due to another PowerShell lesser-known oddity: when you assign a value and place the assignment in braces, the assignment will also be returned. The initial wrong code would use a condition that actually responds to the assignment value.

Whenever you assign 0, ‘’, $false or $null to $result (which all is interpreted as FALSE), the code would return “Result: NO”. Any other assignment would return “Result: YES”.

All of this confusing behavior just because the users’ muscle memory used the operator “=” where “-eq” was really required.


Tweet this Tip! Tweet this Tip!