PowerShell Boolean Logic
Boolean logic is a way to combine True and False values into one answer. You use it when a decision needs more than one test to be true at the same time, or when either of two tests will do.
Require both tests with -and
-and returns True only when every test passes. One failing test makes the whole answer False.
$age = 20
($age -gt 18) -and ($age -lt 65)
($age -gt 18) -and ($age -gt 65)Accept either test with -or
-or returns True when at least one test passes. It returns False only when every test fails.
$score = 95
($score -ge 90) -or ($score -eq 100)
($score -ge 100) -or ($score -lt 50)Flip a value with -not
-not turns True into False. It also turns a False test into True.
$age = 20
-not $true
-not $false
-not ($age -lt 18)Example
$age = 16
$withAdult = $true
"Old enough alone:"
$age -ge 18
"Can enter with an adult:"
($age -ge 18) -or $withAdult
"Needs an adult:"
-not ($age -ge 18)Key points
- Boolean value: a value that is either True or False.
- -and joins two tests and returns True only when both tests are True.
- -or joins two tests and returns True when at least one test is True.
- -not flips a value, turning True into False and False into True.
- Use round brackets to group each test so the whole expression reads clearly.
In this example, the age is 16 and a flag says an adult is present. The first test asks whether 16 alone is old enough, and it is False. The -or test passes because the adult flag is True, and the -not test confirms an adult is still needed.
Note
PowerShell spells these operators with words, -and, -or, and -not, not with symbols.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does ($true -and $false) -or $true return?