about_Switch

简短说明

说明如何使用 开关来处理多个 if 语句。

长说明

若要在脚本或函数中检查条件,请使用 if 语句。 语句if可以检查多种类型的条件,包括变量的值和 对象的属性。

若要检查多个条件,请使用 switch 语句。 语句 switch 等效于一系列 if 语句,但更简单。 语句 switch 列出每个条件和可选操作。 如果条件获得,则执行该操作。

语句 switch 可以使用 $_$switch 自动变量。 有关详细信息,请参阅 about_Automatic_Variables

语法

基本 switch 语句采用以下格式:

Switch (<test-expression>)
{
    <result1-to-be-matched> {<action>}
    <result2-to-be-matched> {<action>}
}

等效 if 语句包括:

if (<result1-to-be-matched> -eq (<test-expression>)) {<action>}
if (<result2-to-be-matched> -eq (<test-expression>)) {<action>}

<test-expression>是在表达式模式下计算以返回值的单个表达式。

<result-to-be-matched>是一个表达式,其值与输入值进行比较。 表达式包括文本值 (返回布尔值的字符串或数字) 、变量和脚本块。

任何未识别为数字的无引号值都被视为字符串。 为了避免混淆或意外的字符串转换,应始终引用字符串值。 将任何表达式括在括号 ()中,创建子表达式,以确保正确计算表达式。

请务必了解该值 <result-to-be-matched> 位于比较表达式的左侧。 这意味着 的结果 <test-expression> 位于右侧,可将其转换为左侧值的类型进行比较。 有关详细信息,请参阅 about_Comparison_Operators

default 是为没有其他匹配项时使用的操作保留的。

自动 $_ 变量包含传递给 switch 语句的表达式的值,可用于计算并在语句范围内 <result-to-be-matched> 使用。

完整的 switch 语句语法如下所示:

switch [-regex | -wildcard | -exact] [-casesensitive] (<test-expression>)
{
    "string" | number | variable | { <value-scriptblock> } { <action-scriptblock> }
    default { <action-scriptblock> } # optional
}

switch [-regex | -wildcard | -exact] [-casesensitive] -file filename
{
    "string" | number | variable | { <value-scriptblock> } { <action-scriptblock> }
    default { <action-scriptblock> }  # optional
}

如果未使用任何参数, switch 的行为与使用 Exact 参数的行为相同。 它对值执行不区分大小写的匹配。 如果值是集合,则按其出现顺序计算每个元素。

语句 switch 必须至少包含一个条件语句。

default当值与任何条件都不匹配时,将触发 子句。 它等效于 else 语句中的 if 子句。 每个switch语句中只允许一个default子句。

switch 具有以下参数:

  • 通配符 - 指示条件是通配符字符串。 如果 match 子句不是字符串,则忽略 参数。 比较不区分大小写。
  • Exact - 指示 match 子句(如果是字符串)必须完全匹配。 如果 match 子句不是字符串,则忽略此参数。 比较不区分大小写。
  • CaseSensitive - 执行区分大小写的匹配。 如果 match 子句不是字符串,则忽略此参数。
  • 文件 - 从文件而不是 <test-expression>获取输入。 如果包含多个 File 参数,则仅使用最后一个参数。 由 语句读取和计算 switch 文件的每一行。 比较不区分大小写。
  • Regex - 执行值与条件的正则表达式匹配。 如果 match 子句不是字符串,则忽略此参数。 比较不区分大小写。 自动 $matches 变量可用于匹配的语句块中。

注意

指定冲突值(如 正则表达式通配符)时,指定的最后一个参数优先,并且忽略所有冲突参数。 还允许多个参数实例。 但是,仅使用列出的最后一个参数。

示例

在以下示例中 switch , 语句将测试值 3 与每个条件进行比较。 当测试值与条件匹配时,将执行该操作。

switch (3)
{
    1 {"It is one."}
    2 {"It is two."}
    3 {"It is three."}
    4 {"It is four."}
}
It is three.

在此简单示例中,即使值 3 匹配,值也会与列表中的每个条件进行比较。 下面的 switch 语句具有两个值 3 的条件。 它演示默认情况下会测试所有条件。

switch (3)
{
    1 {"It is one."}
    2 {"It is two."}
    3 {"It is three."}
    4 {"It is four."}
    3 {"Three again."}
}
It is three.
Three again.

若要指示 switch 在匹配后停止比较,请使用 break 语句。 语句 break 终止 语句 switch

switch (3)
{
    1 {"It is one."}
    2 {"It is two."}
    3 {"It is three."; Break}
    4 {"It is four."}
    3 {"Three again."}
}
It is three.

如果测试值为集合(如数组),则集合中的每个项将按其出现顺序计算。 以下示例计算 4,然后计算 2。

switch (4, 2)
{
    1 {"It is one." }
    2 {"It is two." }
    3 {"It is three." }
    4 {"It is four." }
    3 {"Three again."}
}
It is four.
It is two.

任何 break 语句都应用于 集合,而不是每个值,如以下示例所示。 语句 switch 在值 4 的条件下由 break 语句终止。

switch (4, 2)
{
    1 {"It is one."; Break}
    2 {"It is two." ; Break }
    3 {"It is three." ; Break }
    4 {"It is four." ; Break }
    3 {"Three again."}
}
It is four.

在此示例中,将不是字符串或数字数据的对象传递给 switch。 对 switch 对象执行字符串强制,并评估结果。

$test = @{
    Test  = 'test'
    Test2 = 'test2'
}

$test.ToString()

switch -Exact ($test)
{
    'System.Collections.Hashtable'
    {
        'Hashtable string coercion'
    }
    'test'
    {
        'Hashtable value'
    }
}
System.Collections.Hashtable
Hashtable string coercion

在此示例中,没有匹配大小写,因此没有输出。

switch ("fourteen")
{
    1 {"It is one."; Break}
    2 {"It is two."; Break}
    3 {"It is three."; Break}
    4 {"It is four."; Break}
    "fo*" {"That's too many."}
}

通过添加 default 子句,可以在没有其他条件成功时执行操作。

switch ("fourteen")
{
    1 {"It is one."; Break}
    2 {"It is two."; Break}
    3 {"It is three."; Break}
    4 {"It is four."; Break}
    "fo*" {"That's too many."}
    Default {
        "No matches"
    }
}
No matches

若要使单词“fourteen”与大小写匹配, -Wildcard 必须使用 或 -Regex 参数。

   PS> switch -Wildcard ("fourteen")
       {
           1 {"It is one."; Break}
           2 {"It is two."; Break}
           3 {"It is three."; Break}
           4 {"It is four."; Break}
           "fo*" {"That's too many."}
       }
That's too many.

以下示例使用 -Regex 参数。

$target = 'https://bing.com'
switch -Regex ($target)
{
    '^ftp\://.*$' { "$_ is an ftp address"; Break }
    '^\w+@\w+\.com|edu|org$' { "$_ is an email address"; Break }
    '^(http[s]?)\://.*$' { "$_ is a web address that uses $($matches[1])"; Break }
}
https://bing.com is a web address that uses https

以下示例演示如何使用脚本块作为 switch 语句条件。

switch ("Test")
{
    {$_ -is [String]} {
        "Found a string"
    }
    "Test" {
        "This $_ executes as well"
    }
}
Found a string
This Test executes as well

以下示例处理包含两个日期值的数组。 比较 <value-scriptblock> 每个日期的 Year 属性。 显示 <action-scriptblock> 欢迎消息或 2022 年初之前的天数。

switch ((Get-Date 1-Jan-2022), (Get-Date 25-Dec-2021)) {
    { $_.Year -eq 2021 } {
        $days = ((Get-Date 1/1/2022) - $_).days
        "There are $days days until 2022."
    }
    { $_.Year -eq 2022 } { 'Welcome to 2022!' }
}

如果值与多个条件匹配,则执行每个条件的操作。 若要更改此行为,请使用 breakcontinue 关键字。

break 关键字 (keyword) 停止处理并退出switch语句。

关键字 (keyword) continue 停止处理当前值,但继续处理任何后续值。

以下示例处理一个数字数组,并显示它们是否为奇数或偶数。 使用关键字 (keyword) 跳过continue负数。 如果遇到非数字,则使用 关键字 (keyword) 终止break执行。

switch (1,4,-1,3,"Hello",2,1)
{
    {$_ -lt 0} { continue }
    {$_ -isnot [Int32]} { break }
    {$_ % 2} {
        "$_ is Odd"
    }
    {-not ($_ % 2)} {
        "$_ is Even"
    }
}
1 is Odd
4 is Even
3 is Odd

另请参阅