Switch conditional statesmns allows to execute commands based on conditional expression result.

Switch statements allows you to compare conditional expressions with multiple values, and executes code inside it.

It is an alternative to if-elseif-else statements.

Switch If statements

There are two types of syntaxes Syntax

switch options conditonal_expression{
  {comparison_expression} {#code to execute}
  comparision_value {#code to execute}
  value3 {#code to execute}
  default {#default code executes if none of the values are matched}
}

conditonal_expression: variable or expression that evalauts at runtime

conditional is variable or expression, that evaluates , and result is compared with values inside switch, if value1 is matched, it executes code inside it.

default case executed, when none of values are matched.

values are exact values or expressional conditions using regular expressions or script blocks

break inside value blocks used to exit from switch. if break is not provided, It matches all conditional values along with default block execution.

Options:

optionsDescription
-exact(-e)File not found
-wildcard(-w)file path not found
-casesensitive(-c)Function name is invalid
-regex (-r)Successful
Example:

$marks = 100
switch($marks){
 { $_ -lt 35 } { "failed"; break }
 { $_ -le 50 } { "Second class"; break }
 { $_ -le 60 } { "First Class"; break }
 100 { "Passed and Excellent Marks"; break }
 default { "Passed, Very Good Marks" }
}

Outputs the result is Passed and Excellent Marks

Above example,

$marks value is evalauted to data, and compared againsts multiple expressions. if $marks matches with blocks, It executes the code inside it.

Otherwise, it executes default block

Let’s see some of the examples

Switch regular expressions

$website = "w3schools"

switch -regex ($website) {
    "w3.*" { Write-Host "website started with w3" }
    "website" { Write-Host "Website name is website" }
    default { Write-Host "website not matched" }
}