Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 34 ยท Language Basics

Operators and Comparison

Learn PowerShell comparison operators -eq, -like, -match, -contains and -in, case sensitivity, array-on-the-left filtering, logical operators, ternary and ??.

If you come from another language, the first surprise in PowerShell is that > does not mean "greater than". In a shell, > already means "redirect output to a file", so PowerShell compares with words: -gt, -eq, -like, -match. Once you accept the dash-word style, the operators are consistent, case-insensitive by default, and surprisingly capable, with a few traps around arrays that every scripter hits once.

This lesson covers the comparison operators, string matching with wildcards and regular expressions, testing membership in collections, the logical operators, and the newer ternary, null-coalescing and null-conditional operators of PowerShell 7. It builds on Variables and Types and Strings, Quoting and Here-Strings, and it prepares Conditionals and Loops.

Real PowerShell cannot run on this page, so its code is read-only. The runnable examples are a JavaScript stand-in that models the rules for case, type conversion and arrays on the left. It follows the documented behaviour for the cases shown; real PowerShell converts between many more types than this model.

Comparison, spelled out

-eq / -ne Equal and not equal.
-gt -ge -lt -le Greater and less than.
-like Wildcards with * and ?.
-match Regular expressions.

Never use > or < to compare: they redirect output to a file.

1 / 2

The basic comparison operators

Operator Meaning
-eq, -ne Equal, not equal
-gt, -ge Greater than, greater than or equal
-lt, -le Less than, less than or equal
POWERSHELL
5 -eq 5          # True
'Ada' -ne 'Bob'  # True
10 -gt 3         # True

Why not >? Because in PowerShell 5 > 3 writes the number 5 into a file called 3. It is valid syntax and never an error, which makes it a nasty bug in an if. Always use the dash operators.

Case sensitivity

String comparisons ignore case by default. Prefix the operator with c to be case-sensitive, or i to say "insensitive" explicitly:

POWERSHELL
'Ada' -eq 'ADA'    # True
'Ada' -ceq 'ADA'   # False
'Ada' -ieq 'ADA'   # True

The same applies to -like, -match, -contains, -in, -replace and -split (-clike, -cmatch, -ccontains, -creplace, -csplit).

The left side decides the type

When the two sides have different types, PowerShell converts the right side to the type of the left side. This is why comparisons depend on order:

POWERSHELL
5 -eq '5'         # True   ('5' becomes 5)
'5' -eq 5         # True   (5 becomes '5')
10 -lt '9'        # False  (numbers: 10 < 9)
'10' -lt '9'      # True   (text: '10' sorts before '9')

When you read numbers from files or Import-Csv, they are strings, so cast them before comparing: [int]$row.Age -gt 30. Casting rules are in Variables and Types.

Wildcards with -like

-like and -notlike compare text against a wildcard pattern: * is any run of characters, ? is exactly one character, and [a-c] is one character in a set. The whole string must match.

POWERSHELL
'report.txt' -like '*.txt'     # True
'report.txt' -like 'r?port*'   # True
'report.txt' -like 'port'      # False (must match the whole string)

Wildcards are the same ones you use in Get-ChildItem *.log, so they are quick to read and fast to run.

Regular expressions with -match

-match and -notmatch use regular expressions, which match anywhere in the string unless you anchor with ^ and $:

POWERSHELL
'order-1042' -match '\d+'            # True
'order-1042' -match '^order-(\d+)$'  # True
$Matches[1]                          # 1042

When the left side is a single string and the match succeeds, PowerShell fills the automatic hashtable $Matches: key 0 is the whole match, and further keys are capture groups, numbered or named:

POWERSHELL
'2026-03-01' -match '(?<year>\d{4})-(?<month>\d\d)-(?<day>\d\d)'
$Matches.year    # 2026
$Matches['month']  # 03

Two traps: $Matches is only set for a single string on the left (an array on the left filters and sets nothing), and it keeps old values when a later match fails. Always test the result of -match before reading $Matches. Everything else about regex is in Regular Expressions and Text Processing.

Membership: -contains and -in

Both ask "is this value one of the items in that collection?" They differ only in which side the collection is on.

POWERSHELL
@('red', 'green', 'blue') -contains 'green'   # True: collection on the left
'green' -in @('red', 'green', 'blue')         # True: collection on the right
@('red', 'green') -notcontains 'blue'         # True

Use whichever reads better; -in reads naturally inside Where-Object: $_.Status -in 'Running', 'Starting'. Beware: these test whole items, never substrings. 'abc' -contains 'b' is False, because the single item abc is not equal to b. For a substring use -like '*b*', -match, or 'abc'.Contains('b').

Type tests

-is and -isnot check the type, and -as converts without throwing:

POWERSHELL
42 -is [int]          # True
'42' -is [int]        # False
'42' -as [int]        # 42
'abc' -as [int]       # $null

When the left side is an array

This is the rule that surprises most people: if the left operand is a collection, a comparison operator returns the matching elements instead of True or False.

POWERSHELL
@(1, 2, 3, 2) -eq 2        # 2, 2
@(1, 2, 3, 2) -gt 1        # 2, 3, 2
@('a.log', 'b.txt', 'c.log') -like '*.log'   # a.log, c.log

That is handy for filtering, and dangerous inside an if, because the condition now tests the result, which can be falsy even when a match exists:

POWERSHELL
$items = 0, 1, 2
if ($items -eq 0) { 'found zero' }    # nothing printed! the result is 0, which is false
if ($items -contains 0) { 'found zero' }   # found zero

Use -contains or -in to test for presence. The same hazard explains why you write $null -eq $value, with $null on the left, so a collection in $value is not filtered:

POWERSHELL
if ($null -eq $value) { 'no value' }

Logical operators

Operator Meaning
-and, -or Both, either (they short-circuit)
-xor Exactly one
-not, ! Negation
POWERSHELL
if ($age -ge 18 -and $country -eq 'PT') { ... }
if (-not (Test-Path $file)) { ... }

Use parentheses to make grouping clear. Comparison operators bind tighter than -and and -or, so $a -eq 1 -or $b -eq 2 works without extra brackets.

Other operator families, for reference: arithmetic (+ - * / %; note 7 / 2 is 3.5, the result becomes a decimal when needed), bitwise (-band, -bor, -bxor, -bnot, -shl, -shr), range (1..5), assignment (+=, -=, *=, ??= and so on), and the string operators -f, -join, -split, -replace from the strings lesson.

PowerShell 7 conveniences

Windows PowerShell 5.1 lacks these, so check $PSVersionTable.PSVersion if your script must run there.

POWERSHELL
$mode = $debug ? 'verbose' : 'quiet'       # ternary: condition ? if-true : if-false
$name = $inputName ?? 'anonymous'          # null-coalescing: use the right side when left is $null
$cache ??= @{}                             # assign only when $cache is $null
$len = ${text}?.Length                     # null-conditional: $null instead of an error
Get-Item a.txt && Write-Output 'found'     # run the next only if the first succeeded
Get-Item nope.txt || Write-Output 'missing'  # run the next only if the first failed

?? only reacts to $null, not to 0 or an empty string, which makes it safer than if ($x) for defaults. The null-conditional ?. needs braces around the variable name (${text}?.Length), because $text? would otherwise be read as a variable name that ends with a question mark.

Stand-in: PowerShell comparison rules in JavaScript

This model implements -eq (case-insensitive by default, right side converted to the left's type, an array on the left filters), -like, -match, -contains and -in. The table prints each expression and its result, so you can compare them with the examples above. Arrays print as {...} and a $null result as $null.

JS Comparison operators and arrays on the left

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Each row matches what PowerShell prints for the same expression. The one thing the stand-in does not model is conversion between the many .NET types, which PowerShell performs automatically.

The next example shows the array-on-the-left trap in a condition. A scalar test of the filtered result is falsy when the only match is 0, and contains is the correct test.

JS The if ($items -eq 0) trap

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A match of exactly one element is judged by that element's own truthiness, which is why a lone 0 counts as false. With two or more matches, any non-empty collection is true. These truthiness rules are the same ones PowerShell applies in if.

When the left side might be a collection, or when you want a plain True/False, prefer -contains and -in. When filtering, prefer Where-Object so the intent is obvious.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does 5 > 3 do in PowerShell?

    is the output redirection operator, not a comparison. Use -gt to compare numbers.

  2. 2. What does @(1, 2, 3, 2) -eq 2 return?

    When the left operand is a collection, comparison operators filter it and return the elements that match, not a boolean.
  3. 3. Which test correctly checks that the array $items contains the value 0?

    -eq filters and returns the element 0, which is falsy. -contains returns a real boolean for presence.
  4. 4. What is '10' -lt '9' ?

    The left operand is a string, so the right side is converted to a string too and the comparison is alphabetical: '10' sorts before '9'.
  5. 5. Which operator supplies a default only when the left side is $null (PowerShell 7)?

    ?? returns the right side only when the left side is $null, so 0 and empty strings are kept. -or is a boolean logic operator.

Summary

  • Compare with -eq, -ne, -gt, -ge, -lt, -le; > and < redirect output and must not be used for comparison.
  • String comparisons ignore case unless you use the c forms (-ceq, -cmatch, and so on).
  • The left operand decides the type, so 10 -lt '9' and '10' -lt '9' give different answers.
  • -like uses wildcards (*, ?), -match uses regular expressions and fills $Matches for a single string on the left.
  • -contains has the collection on the left, -in on the right, and both test whole items, never substrings.
  • An array on the left makes a comparison return the matching elements, so test presence with -contains and write $null -eq $x.
  • PowerShell 7 adds ? :, ??, ??=, ?. and the && and || pipeline chain operators.

Next, collect values with Arrays and Hashtables.