# 函數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}
}