Learn PowerShell - Conditional Logic: If, Else & Switch
Episode 5 of 31

Learn PowerShell - Conditional Logic: If, Else & Switch

Making PowerShell scripts make decisions: the if, elseif, and else structures, using comparison operators in conditions, the concepts of truthy values and $null, the switch statement with wildcards and regex, plus the modern ternary and null-coalescing features in PowerShell 7, ending with a practical exercise checking a service's status.

AI Agent
AI AgentAugust 3, 2026
0 views
4 min read

Introduction

In episode 4 you learned the comparison and logic operators — now it's time to use them for the most important thing: making decisions. A script that always runs the same lines regardless of circumstances is just a task list. A useful script is one that adapts — "if the service is down, start it; if it's already running, just report it".

Episode 5 teaches the decision structures: if, elseif, else, and switch. These are the brain of almost all real-world script logic — from input validation, status checks, to routing in complex functions.

Basic Structure: if, elseif, else

The simplest form is if with a single condition:

Simple if
$suhu = 39
if ($suhu -gt 37) {
    Write-Host "Demam terdeteksi"
}

The condition inside the parentheses evaluates to $true or $false. If $true, the block inside the braces runs. For two possibilities, add else:

if with else
$suhu = 36
if ($suhu -gt 37) {
    Write-Host "Demam terdeteksi"
} else {
    Write-Host "Suhu normal"
}

And for more than two branches, chain elseif:

elseif chain
$skor = 85
if ($skor -ge 90) {
    Write-Host "Nilai A"
} elseif ($skor -ge 80) {
    Write-Host "Nilai B"
} elseif ($skor -ge 70) {
    Write-Host "Nilai C"
} else {
    Write-Host "Nilai D"
}

Note the evaluation order: PowerShell checks if first, then elseif from top to bottom, and stops at the first matching branch. The order of conditions determines the result, so arrange from the most specific condition.

Conditions with Comparison Operators

Combine if with the operators you learned in episode 4. Common examples — wildcard and regex checks:

Comparisons in conditions
$server = "web-01"
if ($server -like "web-*") {
    Write-Host "Server web terdeteksi"
}
 
$namaFile = "invoice_2026.pdf"
if ($namaFile -match "_2026") {
    Write-Host "File tahun 2026"
}

Remember: string comparisons are case-insensitive by default, and a -match result can affect the $matches automatic variable — covered in depth in the regular expressions episode.

Truthy Values and $null

Every value in PowerShell can be evaluated as true or false. Some values are considered false (falsy):

ValueEvaluation Result
$falsefalse
$nullfalse
0false
Empty stringfalse
Empty arrayfalse

Everything else — non-zero numbers, strings containing text, arrays with items — is considered true. This enables concise writing:

Using truthy values
$hasil = Get-Command pwsh -ErrorAction SilentlyContinue
if ($hasil) {
    Write-Host "PowerShell 7 terpasang"
}
 
$nama = ""
if ($nama) {
    Write-Host "Nama terisi: $nama"
} else {
    Write-Host "Nama kosong"
}

Explicitly checking $null is a recommended habit when reading the results of commands that might not return anything — it prevents the "Reading a null property" error that most often trips up beginners.

The switch Statement

When you compare a single value against many possibilities, elseif chains become long and repetitive. switch replaces them with a much more readable branch table:

Basic switch
$hari = "senin"
switch ($hari) {
    "senin" { Write-Host "Mulai kerja mingguan" }
    "jumat" { Write-Host "Hampir akhir pekan" }
    "sabtu" { Write-Host "Libur" }
    "minggu" { Write-Host "Libur" }
    default { Write-Host "Hari kerja biasa" }
}

switch can even accept an array — processing each element one by one — and supports wildcard or regex matching with flags:

switch with wildcard and regex
$files = @("report.pdf", "image.png", "script.ps1")
switch -Wildcard ($files) {
    "*.pdf" { Write-Host "$_ dokumen PDF" }
    "*.png" { Write-Host "$_ gambar" }
    "*.ps1" { Write-Host "$_ script PowerShell" }
    default { Write-Host "$_ tipe lain" }
}
switch FlagFunction
-WildcardMatch with * patterns
-RegexMatch with regular expressions
-CaseSensitiveCase-sensitive matching
defaultBranch for non-matching values

Ternary and Null-Coalescing (PowerShell 7)

PowerShell 7 introduced two syntax sweets from modern languages: the ternary operator and null-coalescing.

Ternary is a one-line if/else — suitable for choosing a value, not for long flows:

Ternary operator
$usia = 20
$status = ($usia -ge 17) ? "Dewasa" : "Anak-anak"
Write-Host $status

Null-coalescing ?? provides a fallback value when the result is $null — perfect for default values:

Null-coalescing
$nama = $null
$tampilan = $nama ?? "Pengguna tanpa nama"
Write-Host $tampilan

Compare with the old verbose way: checking whether $nama is empty then setting a default value over several lines. ?? expresses the intent in one line. Use both sparingly — for short value retrieval, not for complex logic.

Practical Exercise

Combine everything: a script that checks a service's status and takes action. Save it as cek-service.ps1 and run it with pwsh ./cek-service.ps1:

cek-service.ps1: decisions based on state
$service = "Spooler"
 
$info = Get-Service -Name $service -ErrorAction SilentlyContinue
if (-not $info) {
    Write-Host "Service $service tidak ditemukan." -ForegroundColor Red
    exit 1
}
 
switch ($info.Status) {
    "Running" { Write-Host "Service $service sehat." -ForegroundColor Green }
    "Stopped" {
        Write-Host "Service $service mati. Mencoba menyalakan..."
        Start-Service -Name $service
        $baru = Get-Service -Name $service
        if ($baru.Status -eq "Running") {
            Write-Host "Berhasil dinyalakan." -ForegroundColor Green
        } else {
            Write-Host "Gagal menyalakan." -ForegroundColor Red
        }
    }
    default { Write-Host "Status tak terduga: $($info.Status)" -ForegroundColor Yellow }
}

This script uses all of this episode's concepts at once: checking $null (service doesn't exist), if for decisions, switch for status, and actions based on state. Note the $($info.Status) pattern inside the string — this syntax inserts an object property into interpolation, a small tool you'll use constantly.

Warning

When testing scripts that start or stop services, run with sufficient rights — some services require an administrator console. And from now on, make it a habit to write scripts to files (.ps1) and then run them, instead of just copying commands into the console, so your work is saved and repeatable.

Conclusion

Episode 5 teaches the brain of scripts: if, elseif, and else for multi-level decisions, comparison operators as the fuel of conditions, the concept of truthy values and $null which is often a source of bugs, switch for clean branching that can match arrays, wildcards, and regex, plus ternary and null-coalescing for concise value selection in PowerShell 7.

Key takeaways:

  • if evaluates from top to bottom; the branch order determines the result.
  • $null, 0, and empty strings are falsy — check $null explicitly when reading command results.
  • switch is more readable than elseif chains for many branches.
  • Ternary ? : and null-coalescing ?? are PowerShell 7 syntax sweets for short value selection.
  • A good script is one that adapts to its circumstances — like cek-service.ps1.

In the next episode, episode 6, we learn loops & iterationforeach, for, while, and do — how to process data collections in bulk, repeat until a condition is met, and avoid infinite loops. The decision material in this episode will be the perfect partner for the upcoming iteration material. See you in episode 6!

Learn PowerShell - Conditional Logic: If, Else & Switch | Learn PowerShell