Edit

PossibleIncorrectUsageOfAssignmentOperator

Severity Level: Information

Description

This rule detects when conditional statements use = or == instead of the PowerShell equality operator (-eq). The rule looks for usages of == and = operators inside if, elseif, while, and do-while statements. In PowerShell, = represents the assignment operator and -eq represents the equality comparison operator.

In many programming languages, == represents the equality comparison operator. When you define == in a PowerShell expression, including conditional statements, PowerShell raises an error because == isn't valid PowerShell syntax. This rule always flags uses of == in conditional statements. However, it doesn't flag uses of = when the right hand side of the conditional uses any commands or expressions.

In these cases, it's likely that the use of the assignment operator is intentional. This construction is often used to concisely assign a value to the variable or property on the left hand side and check whether the assigned value evaluates as true.

Implicit suppression using Clang style

There are some rare cases where assigning a variable inside an if statement is intentional. Instead of suppressing the rule, you can signal that the assignment's intentional by wrapping the expression in extra parentheses. An exception applies when $null is used on the left-hand side because there's no use case for it. For example:

if (($shortVariableName = $SuperLongVariableName['SpecialItem']['AnotherItem'])) {
    ...
}

Example

Noncompliant

if ($a = $b)
{
    ...
}
if ($a == $b)
{

}

Compliant

if ($a -eq $b) # Compare $a with $b
{
    ...
}
if ($a = Get-Something) # Only execute action if command returns something and assign result to variable
{
    Do-SomethingWith $a
}