Powershell

How to negate a condition in PowerShell?

PowerShell uses various conditions for decision-making statements in the scripts. If a specified condition is “True”, then it will run the added command. Otherwise, the code block is executed. PowerShell also supports logical operators, such as “-and”, “-or”, “-xor”, “-not”, and “!”. These logical operators are utilized to connect multiple conditional statements. By utilizing them, you can test numerous conditions. More specifically, logical operators include negation operators like “-not” and “!”, used to negate the condition or, in other words, reverse the condition.

This post will discuss the negation operators and their usage.

How to Negate a Condition in PowerShell?

These are the methods/operators that can be used to negate a condition in PowerShell:

Method 1: Negate a Condition in PowerShell Using “-Not” Operator

The “-Not” operator is a negation operator. It is used to negate conditions in PowerShell that are added afterward.

Example

Now, let’s negate a condition using the “-not” operator. We will use the negation operator in the “if condition”, such as “if(-not(condition))”. The added condition will check if the value of the “$num” variable is greater than 9 and then negates the resultant value due to the “-not” operator:

$num = 6

if (-not($num -gt 9))

{

  "$num is greater than 8"

}

else

{

  "$num is NOT greater than 9"

}

Note that PowerShell is case-sensitive. So, both the “-Not” and “-not” will work the same.

Output

As we have negated the condition, that is why the “if statement” has been executed and the added message is displayed on the screen.

Method 2: Negate a Condition in PowerShell Using “!” Operator

Another negation operator that is used to negate a condition is a “!” operator. It works the same as the “-Not” operator.

Example

In this example, we will utilize the “!” operator for negating the condition “8 -gt 6”:

if (!(8 -gt 6))

{

  "8 is greater than 6"

}

else

{

  "8 is NOT greater than 6"

}

Output

The output shows that the condition has been negated successfully.

Conclusion

To negate a condition in PowerShell, two negation operators “-Not” and “!” can be used. You can add any of the mentioned operators in the “if” statement to negate a condition using the “if (-not(condition))” syntax, or “if (!(condition))”. This post has demonstrated several methods to negate a condition in PowerShell.

About the author

Muhammad Farhan

I am a Computer Science graduate and now a technical writer who loves to provide the easiest solutions to the most difficult problems related to Windows, Linux, and Web designing. My love for Computer Science emerges every day because of its ease in our everyday life.