On this page

If and Switch Statements

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

Control flow determines which code runs based on conditions. PowerShell provides two primary branching constructs: if and switch. Both evaluate expressions and execute different blocks of code depending on the result.


1. if​

The if statement runs a block of code only when a condition is true.

The basic syntax is:


if (<condition>) {

    <code>

}

A condition is any expression that returns $true or $false.

1.1 Basic example​


$age = 20



if ($age -ge 18) {

    "You are an adult."

}

Explanation:

1.2 if / else​


$number = 5



if ($number -gt 10) {

    "Greater than 10"

} else {

    "10 or less"

}

Explanation:

1.3 if / elseif / else​


$score = 75



if ($score -ge 90) {

    "Grade: A"

} elseif ($score -ge 80) {

    "Grade: B"

} elseif ($score -ge 70) {

    "Grade: C"

} else {

    "Grade: D"

}

Explanation:

1.4 Using if with strings​


$name = "Alice"



if ($name -eq "Alice") {

    "Welcome, Alice."

}

String comparisons are case‑insensitive by default.

1.5 Using if with logical operators​


$age = 30

$member = $true



if ($age -ge 18 -and $member) {

    "Access granted."

}

Explanation:


2. switch​

switch evaluates a value against multiple possible matches.

It is cleaner than writing many elseif statements.

Basic syntax:


switch (<value>) {

    <match1> { <code> }

    <match2> { <code> }

    default  { <code> }

}

PowerShell compares the value to each match and runs the corresponding block.


2.1 Basic example​


$color = "green"



switch ($color) {

    "red"   { "Stop" }

    "yellow"{ "Caution" }

    "green" { "Go" }

}

Explanation:


2.2 Using default​


$day = "Monday"



switch ($day) {

    "Saturday" { "Weekend" }

    "Sunday"   { "Weekend" }

    default    { "Weekday" }

}

Explanation:


2.3 Multiple matches​

A single block can match multiple values:


$input = "y"



switch ($input) {

    "y" { "Yes" }

    "Y" { "Yes" }

    "n" { "No" }

    "N" { "No" }

}

This can be simplified:


switch ($input) {

    "y" { "Yes" }

    "n" { "No" }

    default { "Invalid input" }

}

Because comparisons are case‑insensitive by default.


2.4 Pattern matching with switch​

switch supports wildcards when you specify the -Wildcard flag:


$filename = "report_2024.txt"



switch -Wildcard ($filename) {

    "report_*" { "This is a report file." }

    "*.txt"    { "This is a text file." }

}

Explanation:


2.5 Using switch with script blocks​

You can use conditions inside each case:


$number = 15



switch ($number) {

    { $_ -lt 10 } { "Less than 10" }

    { $_ -lt 20 } { "Between 10 and 19" }

    default       { "20 or more" }

}

Explanation:

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Control Flow

Next

Loops