首页 > 代码库 > PowerShell--Switch

PowerShell--Switch

# 函数Switch的学习


<#示例 1 :


1.1 如果变量value的值和下面的数字1匹配那么就返回1的结果(默认的比较操作符为=)


1.2 请分别给变量赋予值 0,1,2,3 查看效果


#>


$value=http://www.mamicode.com/1


Switch($value)




  1 {"Number 1"}


  2 {"Number 2"}


  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}


}



PowerShell--Switch