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
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" }
}