top of page

PowerShell Switch

The Switch Statement in PowerShell is a control flow statement that allows you to test a value against a list of conditions and execute corresponding blocks of code. It's similar to the switch statement in other programming languages like C# or JavaScript.

​

Basic example of the switch statement in PowerShell:

# When you need to have a multitude of conditions and a lot
# cleaner than lots of If statements.

$MySwitchData=3

switch ($MySwitchData) {
     0 {$out = "Blue"}
     1 {$out = "Yellow"}
     2 {$out = "Red"}
     3 {$out = "Green"}
     4 {$out = "Organe"}
     default {$out = "Unknown value"}
}
CLS
Write-Output $out
Write-Output "`n"

PowerShell Switch Cmdlets

Example 2: Using Regex in Switch Statement

Use with regular expressions to match patterns in the switch statement.

$input = "Hello123"

switch -Regex ($input) {
    "^[a-zA-Z]+$" {"The input contains only letters."}
    "^[0-9]+$" {"The input contains only numbers."}
    "^[a-zA-Z0-9]+$" {"The input contains letters and numbers."}
    default {"The input contains special characters."}
}

PowerShell Cmdlet Switch
bottom of page