On this page

Comparison and Logical Operators

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

Comparison and logical operators allow a script to evaluate conditions and make decisions. Comparison operators check whether two values match a specific relationship (equal, greater than, less than, etc.). Logical operators combine multiple conditions into a single expression. These operators are used in if statements, loops, filters, and anywhere a script needs to decide what to do next.


1. Comparison Operators​

Comparison operators evaluate two values and return a boolean ($true or $false).

All comparison operators in PowerShell start with a hyphen (-).

1.1 Equality and inequality​


5 -eq 5      # True

5 -ne 3      # True

5 -eq 3      # False

1.2 Greater than / less than​


10 -gt 5     # True

10 -lt 5     # False

5  -le 5     # True

10 -ge 10    # True

1.3 String comparisons​

PowerShell compares strings case‑insensitively by default:


"hello" -eq "HELLO"   # True

Case‑sensitive versions use a c prefix:


"hello" -ceq "HELLO"  # False

1.4 Pattern matching​

PowerShell supports wildcard matching:


"PowerShell" -like "Power*"     # True

"PowerShell" -notlike "Test*"   # True

Regular expression matching:


"abc123" -match "\d+"     # True

"hello"  -match "\d+"     # False

2. Logical Operators​

Logical operators combine multiple boolean expressions into one.

2.1 and​

Both conditions must be true.


($age -gt 18) -and ($age -lt 65)

If $age is between 19 and 64, the result is True.

2.2 or​

At least one condition must be true.


($color -eq "red") -or ($color -eq "blue")

This is true if $color is "red" or "blue".

2.3 not​

Negates a condition.


-not ($value -eq 10)

Equivalent to:


$value -ne 10

2.4 Combining multiple operators​

PowerShell evaluates expressions left‑to‑right, but parentheses make the logic explicit:


($score -ge 80) -and (($role -eq "admin") -or ($role -eq "manager"))

Explanation:


3. Using comparison and logical operators in real code​

3.1 Filtering values in an array​


$numbers = 1, 5, 10, 15, 20



$large = $numbers | Where-Object { $_ -gt 10 }

Explanation:

3.2 Validating user input​


$age = Read-Host "Enter your age"



if ([int]$age -ge 18 -and [int]$age -le 65) {

    "Valid age range."

} else {

    "Out of range."

}

Explanation:

3.3 Checking multiple conditions​


$name = "Alice"

$loggedIn = $true



if ($name -eq "Alice" -and $loggedIn) {

    "Access granted."

}

Explanation:

3.4 Using pattern matching​


$files = "report1.txt", "image.png", "report2.txt"



$reports = $files | Where-Object { $_ -like "report*.txt" }

Explanation:

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Type Accelerators

Next

Control Flow