当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 关于开关

作者:精品下载站 日期:2024-12-14 02:18:04 浏览:15 分类:玩电脑

关于开关


简短描述

解释如何使用 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 子句。它相当于 if 语句中的 else 子句。每个 switch 语句中只允许有一个 default 子句。

switch 有以下参数:

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

笔记

当指定冲突值时,例如 Regex通配符,最后指定的参数优先,所有冲突参数都将被忽略。还允许参数的多个实例。但是,仅使用列出的最后一个参数。

示例

在以下示例中,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 语句正在测试哈希表中值的类型。您必须使用返回布尔值的表达式来选择要执行的脚本块。

$var = @{A = 10; B = 'abc'}

foreach ($key in $var.Keys) {
    switch ($var[$key].GetType()) {
        { $_ -eq [int32]  }  { "$key + 10 = $($var[$key] + 10)" }
        { $_ -eq [string] }  { "$key = $($var[$key])"           }
    }
}
A + 10 = 20
B = abc

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

$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 关键字停止处理并退出 switch 语句。

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

以下示例处理数字数组并显示它们是奇数还是偶数。使用 continue 关键字会跳过负数。如果遇到非数字,则使用 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

参见

  • about_Break
  • 关于_继续
  • 关于_如果
  • about_Script_Blocks

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯