Conditionals: if, switch, and the Ternary Operator

Making decisions in PowerShell scripts with if, elseif, switch and the ternary operator, including truthiness traps, switch's matching modes and guard clauses.

By The Dark DebuggerUpdated 23 min read

This is the first article in the Scripting section. It covers how PowerShell makes decisions: if/elseif/else, the rules for what counts as true, the switch statement (which is far more capable than in most languages), the PowerShell 7 ternary operator, and the guard-clause style that keeps scripts readable. You should already know the comparison and logical operators and arrays and hashtables. Loops come next, in Loops and Iteration.

Why conditionals deserve care

Picture a cleanup job that deletes old build artifacts. It has a safety switch: when the environment variable DRY_RUN is set, it only reports what it would delete. Someone wants the real thing, sets DRY_RUN=false in the scheduler, and the job carries on doing nothing, night after night:

$env:DRY_RUN = 'false'
if ($env:DRY_RUN) { 'dry run: nothing will be deleted' } else { 'deleting for real' }
[bool]'false'
dry run: nothing will be deleted
True

Flip the logic (a FORCE variable instead of DRY_RUN) and the same bug deletes things it should not. The string 'false' is true in PowerShell. The syntax of if takes five minutes to learn; the rules about what it considers true are where scripts go wrong, so this article spends real time on them.

if, elseif and else

$freeGB = 7.2
if ($freeGB -lt 5) {
    'CRITICAL: under 5 GB free'
}
elseif ($freeGB -lt 10) {
    'WARNING: under 10 GB free'
}
else {
    'OK'
}
WARNING: under 10 GB free

The condition goes in parentheses, and the braces are mandatory even for a one-line body. Conditions are checked top to bottom and only the first true branch runs, so order them from most to least specific.

elseif is one word. Writing else if, as you would in C or JavaScript, fails. In a script file the parser reports Missing statement block after 'else' keyword. At the interactive prompt the error is stranger, because the if on the first line is already a complete statement when you press Enter, so else is treated as a command name:

$freeGB = 7.2
if ($freeGB -lt 5) { 'critical' }
else if ($freeGB -lt 10) { 'warning' }
else: The term 'else' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

The same thing happens at the prompt with a correctly spelled else on its own line after a finished if block. Inside a script file, putting else on the next line is fine; at the prompt, keep } else { on one line.

What counts as true

if converts its condition to a boolean. For real booleans and comparisons there is nothing to think about. For everything else, PowerShell applies these rules:

$cases = [ordered]@{
    '$null'                 = $null
    '0'                     = 0
    '0.0'                   = 0.0
    '-1'                    = -1
    "''"                    = ''
    "' '"                   = ' '
    "'0'"                   = '0'
    "'False'"               = 'False'
    '@()'                   = @()
    '@(0)'                  = @(0)
    '@($null)'              = @($null)
    "@('')"                 = @('')
    '@(0, 0)'               = @(0, 0)
    '@{}'                   = @{}
    '[pscustomobject]@{}'   = [pscustomobject]@{}
}
foreach ($k in $cases.Keys) { '{0,-21} {1}' -f $k, [bool]$cases[$k] }
$null                 False
0                     False
0.0                   False
-1                    True
''                    False
' '                   True
'0'                   True
'False'               True
@()                   False
@(0)                  False
@($null)              False
@('')                 False
@(0, 0)               True
@{}                   True
[pscustomobject]@{}   True

The rules behind that table:

ValueTruthiness
$nullfalse
Numbersfalse only for zero
Stringsfalse only when empty; ' ', '0' and 'False' are all true
Empty collectionfalse
Collection with one elementthe truthiness of that element
Collection with two or more elementstrue, whatever they contain
Any other object (including an empty hashtable)true

The single-element rule is why a comparison that filters a collection can give the wrong answer, as shown in Comparisons against a collection filter it.

Strings that look like booleans

Environment variables, CSV columns, Read-Host answers and command-line output are always strings, so 'false', 'no' and '0' are all true. Compare against the values you accept instead of relying on truthiness:

$env:DRY_RUN = 'false'
$dryRun = $env:DRY_RUN -in 'true', '1', 'yes'
$dryRun
[bool]::Parse('false')
[bool]::Parse('yes')
False
False
MethodInvocationException: Exception calling "Parse" with "1" argument(s): "String 'yes' was not recognized as a valid Boolean."

[bool]::Parse() understands 'true' and 'false' in any case, and throws on anything else, which is a reasonable choice when you want bad configuration to stop the script. The -in list is the forgiving choice. (A [switch] parameter on a script avoids the problem entirely; see Functions and Advanced Functions.)

Commands as conditions

A command's output is converted the same way, which makes "did anything come back?" checks read naturally:

if (Get-ChildItem ./logs -Filter '*.tmp') { 'temp files found' } else { 'no temp files' }
if (Get-ChildItem ./logs -Filter '*.log') { 'log files found' }
if (Test-Path ./logs/app.log) { 'app.log exists' }
no temp files
log files found
app.log exists

No output means false. Be careful with commands that can legitimately output a single 0, '' or $false: those also count as "nothing".

Assignment inside a condition

= assigns, -eq compares. Typing = in a condition is not an error. The assignment happens, and its value is what if tests:

$retries = 3
if ($retries = 0) { 'retries left' } else { 'no retries' }
$retries
no retries
0

The condition silently set $retries to 0. PSScriptAnalyzer warns about this pattern. There is one legitimate use: capturing a result and testing it in one step. If you do it, make sure the next reader can see that it is deliberate:

if ($hit = Select-String -Path ./app.log -Pattern 'ERROR' -List) {
    "first error on line $($hit.LineNumber): $($hit.Line)"
}
first error on line 5: 2026-11-09 08:09:41 ERROR timeout calling bank-gateway

The switch statement

switch compares one value against a list of conditions. The basic form looks like other languages:

$statusCode = 404
switch ($statusCode) {
    200     { 'OK' }
    301     { 'Moved permanently' }
    404     { 'Not found' }
    500     { 'Server error' }
    default { "Unexpected status $statusCode" }
}
Not found

default runs only when nothing else matched. From here on, PowerShell's switch behaves differently from C or JavaScript, in ways that are mostly useful once you know them.

Every matching clause runs

There is no fall-through, but there is also no automatic stop. PowerShell tests every condition and runs every clause that matches. A condition can be a script block, in which $_ is the value being tested:

$port = 443
switch ($port) {
    443              { 'HTTPS' }
    { $_ -lt 1024 }  { 'privileged port' }
    { $_ % 2 -eq 1 } { 'odd number' }
}
HTTPS
privileged port
odd number

break stops the switch after the clause that calls it:

$port = 443
switch ($port) {
    443             { 'HTTPS'; break }
    { $_ -lt 1024 } { 'privileged port' }
}
HTTPS

Use multiple matches when you want to collect several labels (tags for a host, for example) and break when you want "first match wins". There is no syntax for listing several values in one clause; use a script block with -in:

$day = 'Saturday'
switch ($day) {
    { $_ -in 'Saturday', 'Sunday' } { 'weekend: deploys need approval' }
    default                         { 'weekday: normal deploy window' }
}
weekend: deploys need approval

-Wildcard, -Regex and -CaseSensitive

By default each condition is compared with -eq. Switch options change the comparison for the whole statement. -Wildcard uses -like patterns:

$hostname = 'web-prod-03'
switch -Wildcard ($hostname) {
    'web-*'    { 'role: web' }
    'db-*'     { 'role: database' }
    '*-prod-*' { 'environment: production' }
    '*-stg-*'  { 'environment: staging' }
}
role: web
environment: production

-Regex uses regular expressions and fills $Matches for each matching clause, so you can pull data out while you classify:

$line = '2026-11-09 08:09:41 ERROR timeout calling bank-gateway after 30000 ms'
switch -Regex ($line) {
    '^(\S+ \S+) ERROR (.+?) after' { "error at $($Matches[1]): $($Matches[2])" }
    'after (\d+) ms'               { "duration: $([int]$Matches[1] / 1000) s" }
}
error at 2026-11-09 08:09:41: timeout calling bank-gateway
duration: 30 s

Like the operators, switch ignores case unless you add -CaseSensitive:

switch ('ERROR') { 'error' { 'matched (case-insensitive)' } }
switch -CaseSensitive ('ERROR') { 'error' { 'matched' } default { 'no match (case-sensitive)' } }
matched (case-insensitive)
no match (case-sensitive)

Plain comparisons follow the same type conversion as -eq, so a string and a number with the same digits match. -Exact is the default mode and only exists to make that explicit, for example to show that * in a condition is not a wildcard:

switch ('443') { 443 { 'string 443 matched number 443' } }
switch (443) { '443' { 'number 443 matched string 443' } }
switch -Exact ('web-*') { 'web-*' { 'matched literally, no wildcard' } }
string 443 matched number 443
number 443 matched string 443
matched literally, no wildcard

switch over a collection is a loop

Give switch an array and it runs once per element, with $_ set to the current one. Inside, continue moves to the next element and break stops the whole thing:

$codes = 200, 503, 404, 200
switch ($codes) {
    { $_ -ge 500 } { "$_ server error"; continue }
    { $_ -ge 400 } { "$_ client error"; continue }
    default        { "$_ fine" }
}
200 fine
503 server error
404 client error
200 fine
$codes = 200, 503, 404, 200
switch ($codes) {
    { $_ -ge 500 } { "$_ server error, stopping"; break }
    default        { "$_ ok" }
}
200 ok
503 server error, stopping

Note the continue in the first version: without it, 503 would also match -ge 400 and print twice. The flip side of "a collection is a loop" is that an empty collection runs nothing, not even default, while $null is treated as a single value:

switch (@()) { default { 'never printed' } }
'after the empty switch'
switch ($null) { $null { 'matched $null' } default { 'default' } }
after the empty switch
matched $null

If a command feeding a switch might return nothing, and you rely on default to report that, check for the empty case first.

-File: process a file line by line

switch -File reads a file and runs the switch once per line. Combined with -Regex, it is a compact and fast log parser:

$counts = @{ INFO = 0; WARN = 0; ERROR = 0 }
switch -Regex -File ./app.log {
    ' ERROR ' { $counts.ERROR++ }
    ' WARN '  { $counts.WARN++ }
    ' INFO '  { $counts.INFO++ }
}
'{0} info, {1} warnings, {2} errors' -f $counts.INFO, $counts.WARN, $counts.ERROR
5 info, 2 warnings, 2 errors

It streams the file instead of loading it into memory first, so it handles multi-gigabyte logs that would be slow with Get-Content.

$_ belongs to the innermost switch

Inside a switch, $_ is the switch's current value, even when the switch sits inside a ForEach-Object whose $_ you meant:

$fleet = [pscustomobject]@{ Name = 'web01'; Role = 'web' },
         [pscustomobject]@{ Name = 'db01';  Role = 'database' }
$fleet | ForEach-Object {
    switch ($_.Role) {
        'web'      { "$($_.Name) gets the nginx config" }
        'database' { "$($_.Name) gets the postgres config" }
    }
}
 gets the nginx config
 gets the postgres config

Inside the clauses, $_ is the string 'web', which has no Name property. Save the outer object in a variable first:

$fleet = [pscustomobject]@{ Name = 'web01'; Role = 'web' },
         [pscustomobject]@{ Name = 'db01';  Role = 'database' }
$fleet | ForEach-Object {
    $server = $_
    switch ($server.Role) {
        'web'      { "$($server.Name) gets the nginx config" }
        'database' { "$($server.Name) gets the postgres config" }
    }
}
web01 gets the nginx config
db01 gets the postgres config

Conditionals as expressions

if and switch produce output, and you can assign that output directly. This works in Windows PowerShell 5.1 as well as 7, and it removes a lot of "declare a variable, then set it in each branch" code:

$freeGB = 7.2
$level = if ($freeGB -lt 5) { 'critical' } elseif ($freeGB -lt 10) { 'warning' } else { 'ok' }
$level
warning
$env:DEPLOY_ENV = 'staging'
$replicas = switch ($env:DEPLOY_ENV) {
    'prod'    { 6 }
    'staging' { 2 }
    default   { 1 }
}
$replicas
2

Because every matching clause runs, a switch without break can return several values, which arrive as an array:

$hostname = 'web-prod-03'
$tags = switch -Wildcard ($hostname) {
    'web-*'    { 'web' }
    '*-prod-*' { 'production' }
    '*-03'     { 'rack-b' }
}
$tags.Count
$tags -join ','
3
web,production,rack-b

Anything a branch outputs ends up in the variable, including stray output from method calls. Discard what you do not want with $null = (see redirection).

The ternary operator (PowerShell 7)

For a simple either-or value, PowerShell 7 has condition ? ifTrue : ifFalse. It shines inside strings and arguments:

$failed = 2
"Backups: $($failed -eq 0 ? 'all good' : "$failed failed")"
$failed = 0
"Backups: $($failed -eq 0 ? 'all good' : "$failed failed")"
Backups: 2 failed
Backups: all good

Windows PowerShell 5.1 rejects the ? with Unexpected token '?' in expression or statement. The portable equivalent is an if expression inside $( ), which I ran in both versions:

$failed = 2
"Backups: $(if ($failed -eq 0) { 'all good' } else { "$failed failed" })"
Backups: 2 failed

My rule: ternary for two plain values, if for anything with side effects or more than two outcomes, switch for a list of cases. Spacing rules for ? are in the advanced operators article.

Guard clauses

When a function has several preconditions, nesting an if for each one pushes the real work to the right and separates each failure message from the check that causes it:

function Test-DeployRequest {
    param([string]$Version, [string]$Environment, [datetime]$Now)
    if ($Version) {
        if ($Environment -in 'staging', 'prod') {
            if ($Environment -ne 'prod' -or $Now.DayOfWeek -ne 'Friday') {
                "approved: $Version to $Environment"
            }
            else {
                'rejected: no production deploys on Friday'
            }
        }
        else {
            "rejected: unknown environment '$Environment'"
        }
    }
    else {
        'rejected: version is required'
    }
}
Test-DeployRequest -Version '1.4.2' -Environment 'prod' -Now (Get-Date '2026-11-13')
rejected: no production deploys on Friday

Guard clauses invert each check and leave early. Every rule is one line, next to its message, and the happy path sits at the bottom with no indentation:

function Test-DeployRequest {
    param([string]$Version, [string]$Environment, [datetime]$Now)
 
    if (-not $Version) { return 'rejected: version is required' }
    if ($Environment -notin 'staging', 'prod') { return "rejected: unknown environment '$Environment'" }
    if ($Environment -eq 'prod' -and $Now.DayOfWeek -eq 'Friday') {
        return 'rejected: no production deploys on Friday'
    }
 
    "approved: $Version to $Environment"
}
Test-DeployRequest -Version '' -Environment 'prod' -Now (Get-Date '2026-11-10')
Test-DeployRequest -Version '1.4.2' -Environment 'qa' -Now (Get-Date '2026-11-10')
Test-DeployRequest -Version '1.4.2' -Environment 'prod' -Now (Get-Date '2026-11-13')
Test-DeployRequest -Version '1.4.2' -Environment 'prod' -Now (Get-Date '2026-11-10')
rejected: version is required
rejected: unknown environment 'qa'
rejected: no production deploys on Friday
approved: 1.4.2 to prod

Passing $Now in, instead of calling Get-Date inside, is what made the Friday rule testable (13 November 2026 is a Friday). In a real script the guards would usually throw rather than return a message; Error Handling covers that. Parameter validation attributes such as [ValidateSet('staging', 'prod')] can replace some guards entirely, as shown in Functions and Advanced Functions.

Where you'll use this

A service-health classifier

A monitoring job probes each service and writes the results to a CSV. A script turns each row into a status and an action:

Service,Up,LatencyMs,ErrorRate
checkout-api,true,180,0.4
search,true,1250,0.9
payments,true,240,7.5
recommendations,false,0,0
auth,true,620,0.1

The rules are ordered by severity, and only the most severe one should apply. That is switch ($true) with script-block conditions and break: the switch compares $true against each condition's result and stops at the first one that holds.

# Get-ServiceHealth.ps1 - classify each service from the latest health probe results
$probes = Import-Csv ./health.csv
 
foreach ($p in $probes) {
    $latencyMs = [int]$p.LatencyMs
    $errorRate = [double]$p.ErrorRate
 
    # switch ($true) runs the first script block condition that is true; break stops there
    $status = switch ($true) {
        { $p.Up -ne 'true' }  { 'DOWN';     break }
        { $errorRate -ge 5 }  { 'DEGRADED'; break }
        { $latencyMs -ge 1000 } { 'DEGRADED'; break }
        { $latencyMs -ge 500 }  { 'SLOW';     break }
        default               { 'HEALTHY' }
    }
 
    $action = switch ($status) {
        'DOWN'     { 'page on-call' }
        'DEGRADED' { 'open incident' }
        'SLOW'     { 'post in #ops' }
        default    { '' }
    }
 
    '{0,-16} {1,-9} {2,6} ms {3,5:N1} %  {4}' -f $p.Service, $status, $latencyMs, $errorRate, $action
}
./Get-ServiceHealth.ps1
checkout-api     HEALTHY      180 ms   0.4 %
search           DEGRADED    1250 ms   0.9 %  open incident
payments         DEGRADED     240 ms   7.5 %  open incident
recommendations  DOWN           0 ms   0.0 %  page on-call
auth             SLOW         620 ms   0.1 %  post in #ops

Look at the first rule. The obvious way to write "service is down" would be { -not $p.Up }, and it would never fire, because Up came from a CSV and the string 'false' is true:

$p = [pscustomobject]@{ Service = 'recommendations'; Up = 'false' }
if (-not $p.Up) { 'DOWN' } else { 'looks up' }
looks up

The numbers are converted with [int] and [double] for the same reason: CSV gives strings, and string comparisons are alphabetical.

A config-driven deployment selector

CI pipelines often decide where a build goes from the branch name. Keeping the per-environment settings in a JSON file and the branch rules in a switch -Regex keeps both easy to review:

{
  "environments": {
    "prod":    { "replicas": 6, "approval": true,  "regions": ["eu-west-1", "eu-central-1"] },
    "staging": { "replicas": 2, "approval": false, "regions": ["eu-west-1"] },
    "dev":     { "replicas": 1, "approval": false, "regions": ["eu-west-1"] }
  }
}
# Select-Deployment.ps1 - map a Git branch to a deployment target using deploy.json
param(
    [Parameter(Mandatory)][string]$Branch,
    [string]$ConfigPath = './deploy.json'
)
 
if (-not (Test-Path $ConfigPath)) {
    throw "Config file '$ConfigPath' not found"
}
 
$target = switch -Regex ($Branch) {
    '^main$'               { 'prod';    break }
    '^release/\d+\.\d+$'   { 'staging'; break }
    '^(feature|fix)/[\w-]+$' { 'dev';     break }
    default                { $null }
}
 
if (-not $target) {
    "No deployment for branch '$Branch'"
    return
}
 
$settings = (Get-Content $ConfigPath -Raw | ConvertFrom-Json).environments.$target
$approval = if ($settings.approval) { 'manual approval required' } else { 'automatic' }
 
"$Branch -> ${target}: $($settings.replicas) replica(s) in $($settings.regions -join ', '), $approval"
./Select-Deployment.ps1 -Branch main
./Select-Deployment.ps1 -Branch release/2.7
./Select-Deployment.ps1 -Branch feature/faster-search
./Select-Deployment.ps1 -Branch experiment
main -> prod: 6 replica(s) in eu-west-1, eu-central-1, manual approval required
release/2.7 -> staging: 2 replica(s) in eu-west-1, automatic
feature/faster-search -> dev: 1 replica(s) in eu-west-1, automatic
No deployment for branch 'experiment'

Everything from this article is in there: a guard clause for the missing config file, a switch -Regex used as an expression with break so the first rule wins, a default that returns $null, an if that leaves early, and an if expression for the approval text. Here $settings.approval is safe to test directly because ConvertFrom-Json produces real booleans from JSON true/false; it is CSV and environment variables that give you strings. (${target} needs braces because a colon follows it.)

Common mistakes

Writing else if. PowerShell's keyword is elseif. else if fails with Missing statement block after 'else' keyword. in a script, or with "the term 'else' is not recognized" at the prompt.

Testing a string that holds a boolean. 'false', '0' and 'no' are true. Compare against the accepted values ($env:DRY_RUN -in 'true', '1', 'yes'), use [bool]::Parse(), or use a [switch] parameter.

= instead of -eq. if ($retries = 0) assigns 0 and evaluates as false; no error is raised. Read every condition containing a single = twice.

Forgetting that every switch clause runs. Overlapping conditions (-ge 500 and -ge 400, or 'web-*' and '*-prod-*') all fire. Add break (or continue when switching over a collection) when you mean first-match-wins.

Using $_ from an outer pipeline inside switch. The switch replaces it. Save the outer object ($server = $_) before the switch.

Relying on default for empty input. switch (@()) runs no clauses at all. Check for the empty case before the switch.

Summary

  • if (...) { } elseif (...) { } else { }: braces are required, elseif is one word, and only the first true branch runs. At the prompt, keep } else { on one line.
  • Falsy values: $null, 0, '', empty collections, and single-element collections holding a falsy value. Everything else is true, including ' ', '0', 'False', @{} and any collection with two or more elements.
  • External data is text. Test string flags against explicit values or parse them; never rely on the truthiness of 'false'.
  • switch runs every matching clause; break stops it, and over a collection continue moves to the next element. Conditions can be values, script blocks ({ $_ -gt 5 }), wildcards (-Wildcard), regexes with $Matches (-Regex) or case-sensitive (-CaseSensitive).
  • switch over an array loops; switch -File streams a file line by line; an empty collection runs nothing, not even default.
  • if and switch can be assigned ($x = if ...), in 5.1 and 7. A switch with several matches returns an array.
  • The ternary ? : is PowerShell 7 only; use $(if ... else ...) in code that must run on 5.1.
  • Guard clauses (if (-not $ok) { return ... }) keep each rule next to its failure and the normal path unindented.

Exercises

Exercise 1: Which letters print?easy

Predict which of these lines print their letter, then run them to check:

if ('False')     { 'A' }
if (@(0))        { 'B' }
if (' ')         { 'C' }
if (@{})         { 'D' }
if ([int]'0')    { 'E' }
if (@($null, 1)) { 'F' }
Show Solution

Running the six lines prints:

A
C
D
F

'False' and ' ' are non-empty strings. @(0) is a one-element collection, so it takes the truthiness of 0. An empty hashtable is still an object. [int]'0' is the number zero. @($null, 1) has two elements, which is always true regardless of what they are.

Exercise 2: Disk usage levelseasy

For the usage percentages 45, 82 and 97, assign a level with a single if/elseif/else expression: critical at 95 or more, warning at 80 or more, otherwise ok. Print one line per value.

Show Solution
foreach ($used in 45, 82, 97) {
    $level = if ($used -ge 95) { 'critical' } elseif ($used -ge 80) { 'warning' } else { 'ok' }
    "$used% -> $level"
}
45% -> ok
82% -> warning
97% -> critical

The most severe threshold is tested first. Reverse the order and 97 would stop at -ge 80 and be reported as a warning.

Exercise 3: Classify files by namemedium

Classify each file as archive (ends in .gz), log (contains .log), config (ends in .json) or other, using switch -Wildcard as an expression. app.log.1.gz must count as an archive, not a log.

$files = 'app.log', 'app.log.1.gz', 'settings.json', 'backup-2026-11-09.tar.gz', 'notes.txt'
Show Solution
$files = 'app.log', 'app.log.1.gz', 'settings.json', 'backup-2026-11-09.tar.gz', 'notes.txt'
foreach ($f in $files) {
    $kind = switch -Wildcard ($f) {
        '*.gz'   { 'archive'; break }
        '*.log*' { 'log'; break }
        '*.json' { 'config'; break }
        default  { 'other' }
    }
    '{0,-26} {1}' -f $f, $kind
}
app.log                    log
app.log.1.gz               archive
settings.json              config
backup-2026-11-09.tar.gz   archive
notes.txt                  other

app.log.1.gz matches both *.gz and *.log*. Putting the archive rule first and ending each clause with break makes the first match win; without break, $kind would be the array archive, log.

Exercise 4: Find the slowest requestmedium

requests.log contains lines like these:

2026-11-09 08:00:03 GET /api/cart 200 took 84 ms
2026-11-09 08:00:04 GET /api/search?q=boots 200 took 1312 ms
2026-11-09 08:00:04 POST /api/checkout 201 took 402 ms
2026-11-09 08:00:05 GET /api/cart 200 took 77 ms
2026-11-09 08:00:07 GET /api/search?q=socks 200 took 958 ms

Using switch -Regex -File, find the slowest request and print its duration and the full line.

Hint

Inside a -File switch, $_ is the current line and $Matches holds the capture groups of the clause that matched. Convert the captured number before comparing it.

Show Solution
$slowest = 0
$slowestLine = ''
switch -Regex -File ./requests.log {
    'took (\d+) ms' {
        if ([int]$Matches[1] -gt $slowest) {
            $slowest = [int]$Matches[1]
            $slowestLine = $_
        }
    }
}
"slowest: $slowest ms"
$slowestLine
slowest: 1312 ms
2026-11-09 08:00:04 GET /api/search?q=boots 200 took 1312 ms

Without [int], the comparison would be between strings, and '958' sorts after '1312'.

Exercise 5: Validate a maintenance request with guard clauseshard

Write Test-MaintenanceWindow with parameters Ticket, DurationMinutes and Start. Reject the request if the ticket does not look like CHG- followed by at least four digits, if the duration is not between 1 and 240 minutes, or if it starts between 07:00 and 22:00. Otherwise accept it. Use guard clauses, and test one failing case per rule plus one valid request.

Show Solution
function Test-MaintenanceWindow {
    param([string]$Ticket, [int]$DurationMinutes, [datetime]$Start)
 
    if ($Ticket -notmatch '^CHG-\d{4,}$') { return "rejected: '$Ticket' is not a change ticket" }
    if ($DurationMinutes -le 0 -or $DurationMinutes -gt 240) { return 'rejected: duration must be 1-240 minutes' }
    if ($Start.Hour -ge 7 -and $Start.Hour -lt 22) { return 'rejected: must start between 22:00 and 07:00' }
 
    "accepted: $Ticket, $DurationMinutes min from $($Start.ToString('yyyy-MM-dd HH:mm'))"
}
Test-MaintenanceWindow -Ticket 'INC-1234' -DurationMinutes 60 -Start (Get-Date '2026-11-10 23:00')
Test-MaintenanceWindow -Ticket 'CHG-20931' -DurationMinutes 300 -Start (Get-Date '2026-11-10 23:00')
Test-MaintenanceWindow -Ticket 'CHG-20931' -DurationMinutes 90 -Start (Get-Date '2026-11-10 14:00')
Test-MaintenanceWindow -Ticket 'CHG-20931' -DurationMinutes 90 -Start (Get-Date '2026-11-10 23:30')
rejected: 'INC-1234' is not a change ticket
rejected: duration must be 1-240 minutes
rejected: must start between 22:00 and 07:00
accepted: CHG-20931, 90 min from 2026-11-10 23:30

Each rule is a single line with its own message, and the accepted path is the last line of the function. Adding a fourth rule (say, no changes during a freeze period) is one more guard, not another level of nesting. The test calls cover every branch, which is what makes guard-clause functions easy to trust.


Tested with: PowerShell 7.6.9 on Ubuntu 24.04 (WSL2) and Windows PowerShell 5.1 (5.1.26100) on Windows 11, November 2026. Every example was run as shown in PowerShell 7.6.9, the interactive-prompt examples by piping them into pwsh -NoProfile and the two scripts from files. I also ran the if and switch expressions, the $(if ...) ternary replacement and the [bool]'False' check in Windows PowerShell 5.1, with identical results. The else if message quoted for script files comes from running the same three lines as a .ps1 file.

Was this page helpful?
The Dark Debugger

Written by The Dark Debugger

Engineer documenting the things that took me too long to learn, so they take you less time. Every PowerShell tutorial here is tested end to end before publishing.