Negate a Condition in PowerShell

Rohan Timalsina Apr 01, 2022 Jan 23, 2022
Negate a Condition in PowerShell

PowerShell has different decision-making statements for executing the codes like other programming languages. You can use conditions for decision-making in the PowerShell scripts. The scripts perform different actions based on those decisions. If the condition is true, it will execute one command, and if the condition is false, it will execute the other command.

One of the most used statements in PowerShell is the If statement. It has three types: if statement, if-else statement, and nested if statement. PowerShell also uses a switch statement as a conditional statement.

Here is a simple example of the if statement.

if(5 -lt 7){
    Write-Host "5 is less than 7"
}

If 5 is less than 7, it executes the Write-Host command.

Output:

5 is less than 7

The logical operators connect the conditional statements in the PowerShell, which allows you to test for multiple conditions. The PowerShell supports -and, -or, -xor, -not, and ! logical operators. This tutorial will teach you to negate a condition in the PowerShell.

Use -not Operator to Negate a Condition in the PowerShell

-not is a logical operator that negates the statement in the PowerShell. You can use a -not operator to negate a condition in the PowerShell.

if (-not (5 -lt 7)){
    Write-Host "5 is less than 7"
}

This time, it does not print any output because the condition becomes negative with the -not operator. It states 5 is not less than 7, which is false.

Now, let’s test another condition, 5 is greater than 7 with the -not operator.

if (-not (5 -gt 7)){
    Write-Host "5 is less than 7"
}

It prints the output because 5 is not greater than 7 is true.

Output:

5 is less than 7

Use ! Operator to Negate a Condition in the PowerShell

You can also use the ! operator to negate a condition in the PowerShell. It is the same as the -not operator.

We have two variables, $a and $b, with the value below.

$a=3; $b=9

Here, the condition becomes $a is not less than $b with the ! operator. If the condition is true, it will execute the first command, and if the condition is false, the second command will be executed.

if (! ($a -lt $b)){
    Write-Host "$a is greater than $b"
}
else{
    Write-Host "$a is less than $b"
}

Output:

3 is less than 9
Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website