Menu
CoddyTech

The Switch Statement

Part of the PowerShell Basics section of Coddy's PowerShell journey. Lesson 14 of 28.

switch compares one value with a list of cases and runs the block of each case that matches. default runs when nothing matched:

$size = Read-Host "Size"
switch ($size) {
    "S" { Write-Output "Small cup" }
    "M" { Write-Output "Medium cup" }
    "L" { Write-Output "Large cup" }
    default { Write-Output "We have S, M and L" }
}

With the input m, this prints Size: m and Medium cup: like -eq, switch ignores case. With XL, it prints We have S, M and L.

The cases can be numbers too. Add -Wildcard to use patterns such as "*.txt":

switch -Wildcard ("notes.txt") {
    "*.txt" { Write-Output "Text file" }
    "*.csv" { Write-Output "Data file" }
}

This prints Text file.

challenge icon

Challenge

Easy

Write the command handler of a small service script.

  1. Read a command with the prompt Command.
  2. For start, print Starting the service. For stop, print Stopping the service. For status, print The service is running.
  3. For anything else, print Unknown command: followed by the command as it was typed.

Commands are matched whatever their case, so STOP works like stop. With the input STOP, your script prints:

Command: STOP
Stopping the service

With restart, the second line is Unknown command: restart.

Try it yourself

$cmd = Read-Host "Command"
# Handle start, stop, status and anything else with a switch
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in PowerShell Basics