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
EasyWrite the command handler of a small service script.
- Read a command with the prompt
Command. - For
start, printStarting the service. Forstop, printStopping the service. Forstatus, printThe service is running. - 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 serviceWith 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in PowerShell Basics
5Project: Password Checker
Project OverviewLength Check3Input And Conditions
Reading InputComparison OperatorsIf, ElseIf And ElseThe Switch StatementRecap - Ticket Price