0
0
PowerShellscripting~5 mins

Switch statement in PowerShell

Choose your learning style9 modes available
Introduction

A switch statement helps you choose what to do based on different values. It makes your script easier to read when you have many options.

You want to run different code depending on a user's choice.
You need to check a variable against many possible values.
You want to replace many if-else statements with cleaner code.
You want to handle different commands or inputs in a script.
Syntax
PowerShell
switch (<expression>) {
    <value1> { <code1> }
    <value2> { <code2> }
    default { <defaultCode> }
}

The switch keyword starts the statement.

Each value is checked against the expression. If it matches, the code inside runs.

Examples
This example checks the value of $color and prints a message.
PowerShell
switch ($color) {
    'red' { Write-Output 'Stop' }
    'green' { Write-Output 'Go' }
    default { Write-Output 'Wait' }
}
This checks the number 5 and returns 'Five'.
PowerShell
switch (5) {
    1 { 'One' }
    5 { 'Five' }
    default { 'Other' }
}
Sample Program

This script checks the day and prints a message for Tuesday.

PowerShell
$day = 'Tuesday'
switch ($day) {
    'Monday' { Write-Output 'Start of work week' }
    'Tuesday' { Write-Output 'Second day' }
    'Friday' { Write-Output 'Almost weekend' }
    default { Write-Output 'Just another day' }
}
OutputSuccess
Important Notes

You can use default to catch any value not listed.

Switch statements can match strings, numbers, or even patterns.

Summary

Switch statements help pick actions based on values.

They make code cleaner than many if-else checks.

Use default to handle unexpected cases.