Skip to content
AgileLogics
6 min read

Operators

Prerequisites: Strings, Numbers and math

PowerShell's comparison operators are words starting with a dash, not symbols — because > and < are used for redirection.

Comparison

5 -eq 5
5 -ne 3
10 -gt 9
3 -le 3
'apple' -lt 'banana'
'ADA' -eq 'ada'
'ADA' -ceq 'ada'
True
True
True
True
True
True
False
Operator Meaning
-eq, -ne equal, not equal
-gt, -ge greater than, greater or equal
-lt, -le less than, less or equal

Text comparisons are case-insensitive by default. Prefix with c for case-sensitive versions: -ceq, -clike, -cmatch.

Wildcards and regular expressions

'report.pdf' -like '*.pdf'
'report.pdf' -notlike '*.txt'
'Order 1042 shipped' -match '\d+'
$Matches[0]
'ada@example.com' -match '^[^@]+@(.+)$'
$Matches[1]
'a1b22c333' -replace '\d+', '#'
True
True
True
1042
True
example.com
a#b#c#
  • -like uses wildcards (*, ?).
  • -match uses regular expressions; after a match, the automatic $Matches variable holds the matched text and groups. Test patterns in the Regex Tester.
  • -replace substitutes regex matches.

Logical operators

$age = 20
$hasTicket = $true
$age -ge 18 -and $hasTicket
$age -lt 13 -or $age -gt 65
-not $hasTicket
!$hasTicket
True
False
False
False

Collections

$fruits = 'apple', 'banana', 'cherry'
$fruits -contains 'banana'
'kiwi' -in $fruits
$fruits -like 'b*'
True
False
banana

With a collection on the left, comparison operators act as filters, returning the matching items.

PowerShell 7 shortcuts

$count = 3
$count -gt 2 ? 'many' : 'few'

$nickname = $null
$nickname ?? 'Guest'
$nickname ??= 'Anonymous'
$nickname
many
Guest
Anonymous
  • condition ? a : b — the ternary operator.
  • $x ?? default — use a default when $x is $null.
  • $x ??= value — assign only if $x is $null.

Common mistakes

  • Writing if ($a > 5) — > redirects output to a file named 5. Use -gt.
  • $null comparisons: put $null on the left ($null -eq $x), because with a collection on the left, -eq filters instead of comparing.