# 函数Switch的学习shell
<#示例 1 :app
1.1 若是变量value的值和下面的数字1匹配那么就返回1的结果(默认的比较操做符为=)less
1.2 请分别给变量赋予值 0,1,2,3 查看效果ide
#>函数
$value=1学习
Switch($value)code
{ orm
1 {"Number 1"}ci
2 {"Number 2"}get
3 {"Number 3"}
}
==============================================================================
<#示例2:
2.1 自定义比较条件当多个条件知足的时候,switch将返回多个值 ,见《Mastering Powershell》--217页
2.2 尝试10, 150,210这,四个值,看看返回什么结果
#>
$value01 =210
switch ($value01)
{
{$_ -gt 100} { "$value01 is greater than 100" } #注意:若是条件申明有表达式须要使用{}大括号,进行自定义条件
150 {"hi"}
{($_ -gt 200) -and ($_ -le 300)} {"$value01 is greater than 200 but less than 300" }
}
==============================================================================
<#示例3:
3.1 运行了示例2后,咱们知道当Switch没有知足任何一个条件的时候将不返回结果,其实咱们能够定义没有知足条件的话,返回默认结果
3.2 其实和if的Else同样,以下英文解释
In a similar manner as an If statement, the Switch statement executes code only if at least one of
the specified conditions is met. The keyword, which for the If statement is called Else, is called
default for Switch statement. When no other condition matches, the default clause is run.
#>
$value02= 15 # 请尝给变量value02分配 5,6,7,15这些值时,返回的结果
switch ($value02)
{
{$_ -le 5} {"$_ is a number from 1 to 5"}
6 {"Number is 6"}
{ (($_ -gt 6) -and ($_ -le 10)) } { "$_ is a number from 7 to 10" }
default { "$_ is a number outside the range of from 1 to 10"}
}
<#示例4:
4.1 经过上面的示例,咱们已经知道Switch函数有多个条件知足的时候会返回多个结果;若是我但愿仅返回一个结果,那么咱们能够使用关键字
"break",只要一个条件知足就退出申明(即再也不执行下面的条件)
4.2 英文解释以下
If you'd like to receive only one result, while consequently making sure that only the first applicable
condition is performed, then append the break statement to the code.
In fact, now you get only the first applicable result. The keyword break indicates that no more
processing will occur and the Switch statement will exit.
#>
$value03 = 5 # 请尝试给变量value03分配 50,60,5 这些值,查看返回的结果
Switch ($value03)
{
50 { "the number 50"; break } #当咱们输入50的时候,3个条件都知足了,应该返回3个结果,可是使用了break只会返回一个结果
{$_ -gt 10} {"larger than 10"; break}
{$_ -is [int]} {"Integer number"; break}
}