Operators, if, switch and loops

PowerShell · Essentials · 12 min

PowerShell's dash-style operators and case-insensitive defaults trip up everyone coming from other languages.

Comparison operators are words with a dash, because > and < are redirection: -eq -ne -gt -ge -lt -le. String operators: -like (wildcards * and ?), -match (regex, fills the automatic $Matches variable), -replace (regex replace). Membership: -contains (collection on the left) and -in (collection on the right). All are case-insensitive by default; prefix with c for case-sensitive: -ceq, -cmatch.

A surprise: with a collection on the left, comparison operators filter instead of returning a boolean. 1, 5, 9 -gt 4 returns 5, 9. That is why $null -eq $x is written with $null first.

Branching: if (...) { } elseif (...) { } else { }. switch matches a value against cases and supports -Wildcard, -Regex and script-block conditions. Unlike C, every matching case runs unless you break, and given an array, switch processes each element.

Loops:

  • foreach ($item in $collection) { } statement: fast, for data already in memory,
  • ForEach-Object { $_ } cmdlet: streams pipeline input one item at a time,
  • for ($i = 0; $i -lt 10; $i++) { }, while, do { } while/until.

1..5 is a range, and logical operators are -and, -or, -not (or !).

Example

$n = 7
if ($n -gt 5) { 'big' } elseif ($n -gt 2) { 'medium' } else { 'small' }   # big
'Hello' -eq 'hello'               # True   (case-insensitive by default)
'Hello' -ceq 'hello'              # False
'report.csv' -like '*.csv'        # True
'v2.15' -match 'v(\d+)\.(\d+)'    # True
$Matches[1]                       # 2
'b' -in 'a', 'b', 'c'             # True
1, 5, 9 -gt 4                     # 5 / 9   (a collection on the left filters!)
switch -Wildcard ('error.log') {
  '*.log' { 'log file' }          # log file
  'err*'  { 'error-ish' }         # error-ish  (every matching case runs)
}
foreach ($i in 1..3) { "item $i" }      # item 1 / item 2 / item 3
$i = 0; while ($i -lt 3) { $i++ }; $i   # 3

Remember

  • -eq -gt -like -match: case-insensitive unless prefixed with c
  • A collection on the left of a comparison filters it
  • switch runs every matching case; foreach statement vs ForEach-Object cmdlet

Watch out for

  • Writing if ($x > 5): > is redirection and creates a file named 5.

Check yourself

  1. What does `if ($count > 10) { ... }` actually do?
  2. What does `'a','b','a' -eq 'a'` return?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators

Operators, if, switch and loops · PowerShell · Topolearn