Logical operators help you combine or change true/false conditions in scripts. They let you make decisions based on multiple rules.
0
0
Logical operators (-and, -or, -not) in PowerShell
Introduction
Check if two conditions are both true before running a command.
Run a command if at least one of several conditions is true.
Reverse a condition to run code when something is not true.
Filter data by combining multiple checks.
Control script flow with complex true/false logic.
Syntax
PowerShell
condition1 -and condition2 condition1 -or condition2 -not condition
-and means both conditions must be true.
-or means at least one condition must be true.
-not reverses the condition's result.
Examples
This checks if $a is less than 10 and $b is greater than 5. Both must be true.
PowerShell
$a = 5 $b = 10 if ($a -lt 10 -and $b -gt 5) { "Both true" }
This runs if $a equals 3 or $b equals 5. Only one needs to be true.
PowerShell
$a = 3 $b = 2 if ($a -eq 3 -or $b -eq 5) { "At least one true" }
This reverses $flag. If $flag is false, the code runs.
PowerShell
$flag = $false if (-not $flag) { "Flag is false" }
Sample Program
This script checks if a person is 18 or older and has an ID. If both are true, it allows entry. If no ID, it says ID required. Otherwise, it denies entry.
PowerShell
$age = 20 $hasID = $true if ($age -ge 18 -and $hasID) { Write-Output "Allowed entry" } elseif (-not $hasID) { Write-Output "ID required" } else { Write-Output "Not allowed" }
OutputSuccess
Important Notes
Use parentheses to group conditions for clarity, like: if (($a -lt 10) -and ($b -gt 5))
Logical operators work with boolean values: $true or $false.
PowerShell evaluates conditions left to right and stops early if possible (short-circuit).
Summary
-and means both conditions must be true.
-or means at least one condition must be true.
-not reverses a condition's true/false value.