Search notes:

PowerShell: switch statement

Simple switch statement

The following scriptlet demonstrates the most simple form of a switch statement:
$num = 4

switch ($num) {

  1       { 'one'   }
  2       { 'two'   }
  3       { 'three' }
  4       { 'four'  }
  5       { 'five'  }
  default { '?'     }

}
Github repository about-powershell, path: /language/statement/switch/num-to-text.ps1

Evaluation of expressions

It is possible to evaluate expressions in order to determine which script block es executed. The automatic variable $_ is bound to the object that is tested in the switch($obj) condition and also in the corresponding evaluated block:
set-strictMode -version 2

function category ($thing) {

   switch ($thing) {

      { $_ -in 'apple', 'pear', 'orange' } {
         write-host "$_ is a fruit"
      }
      { $_ -in 'foo', 'bar', 'baz' } {
         write-host "$_ is a metasyntactic variable"
      }
      { $_.GetType().Name -eq 'Int32' } {
         write-host "$_ is an int32"
      }
      default {
        write-host "I don't know what $_ is"
      }

   }
}

category  baz
# baz is a metasyntactic variable

category  42
#
# 42 is an int32

category  orange
#
# orange is a fruit

category  ?
#
# I don't know what ? is
Github repository about-powershell, path: /language/statement/switch/eval.ps1

Assignment

The result of a switch statement can be assigned to a variable:
set-strictMode -version 3

$num = 2

$txt = switch ($num) {
  1 { 'one'   }
  2 { 'two'   }
  3 { 'three' }
}

write-host "txt = $txt"
Github repository about-powershell, path: /language/statement/switch/assignment.ps1

Using the break statement

In a switch statement, the break statement makes sure that the switch statement is exited without testing the following conditions:
$num = 42

switch ($num) {

  { $_ -le   9 } { "$_ has one digit"             ; break }
  { $_ -le  99 } { "$_ has two digits"            ; break }
  { $_ -le 999 } { "$_ has three digits"          ; break }
    default      { "$_ has more than three digits"        }

}
Github repository about-powershell, path: /language/statement/switch/break.ps1

See also

Other statements such as the if statement.

Index