powershell 的 swith 语句强大的令人无法相信哈
1. 最基本的语句
$a = 5
switch ($a)
{
1 {"The color is red."}
2 {"The color is blue."}
3 {"The color is green."}
4 {"The color is yellow."}
5 {"The color is orange."}
6 {"The color is purple."}
7 {"The color is pink."}
8 {"The color is brown."}
default {"The color could not be determined."}
}
========================================================
2. 多值的时候
$a = 5
switch ($a)
{
{($_ -eq 1) -or ($_ -eq 2) -or ($_ -eq 3)}
{"The color is red."}
4 {"The color is yellow."}
5 {"The color is orange."}
6 {"The color is purple."}
7 {"The color is pink."}
8 {"The color is brown."}
default {"The color could not be determined."}
}
Note: case 可以试条件表达式的 {($_ -eq 1) -or ($_ -eq 2) -or ($_ -eq 3)}
在如:$myNumber = 3
$arrA = 1, 3, 5, 7, 9
$arrB = 2, 4, 6, 8, 10
switch ($myNumber)
{
{$arrA -contains $_} { write-host "Odd" }
{$arrB -contains $_} { write-host "Even" }
}
=========================================================
3. 可以用wildcard 参数
如:
$a = "d14151"
switch -wildcard ($a)
{
"a*" {"The color is red."}
"b*" {"The color is blue."}
"c*" {"The color is green."}
"d*" {"The color is yellow."}
"h*" {"The color is brown."}
default {"The color could not be determined."}
}
在如:
$a = "d14151"
switch -wildcard ($a)
{
"?14150" {"The color is red."}
"?14151" {"The color is blue."}
"?14152" {"The color is green."}
"?14153" {"The color is yellow."}
default {"The color could not be determined."}
}
=======================================================================
4. 使用正则表达式
如:一个变量,以字母开头后面跟写数字,开头的a,b,c,d 决定一种颜色,这时就要用正则表达式才行了
$a = "r14151"
switch -regex ($a)
{
"[a-d]" {"The color is red."}
"[e-g]" {"The color is blue."}
"[h-k]" {"The color is green."}
"[l-o]" {"The color is yellow."}
"[p-s]" {"The color is orange."}
default {"The color could not be determined."}
}
在如
$a = "14151"
switch -regex ($a)
{
"\d{5}" {"The color is yellow.”; break}
"\d{4}" {"The color is orange.”; break}
"\d{3}" {"The color is purple.”; break}
"\d{2}" {"The color is pink.”; break}
"\d{1}" {"The color is brown.”; break}
default {"The color could not be determined."}
}
#Result PS>The color is yellow
===========================================================
5. 用 Arrays $a = 21, 38, 6
switch ($a)
{
1 {"The color is red."}
2 {"The color is blue."}
3 {"The color is green."}
4 {"The color is yellow."}
5 {"The color is orange."}
6 {"The color is purple."}
7 {"The color is pink."}
8 {"The color is brown."}
}
#Result PS>The color is purple.