Menu
CoddyTech

Switch 语句

本课属于 Coddy PowerShell 学习旅程的“PowerShell 基础”单元。第 14 课,共 28 课。

switch 将一个值与一系列 case 进行比较,并运行每个匹配到的 case 的代码块。当没有任何匹配时,运行 default:

$size = Read-Host "Size"
switch ($size) {
    "S" { Write-Output "Small cup" }
    "M" { Write-Output "Medium cup" }
    "L" { Write-Output "Large cup" }
    default { Write-Output "We have S, M and L" }
}

输入 m 时,这会输出 Size: m 和 Medium cup:与 -eq 一样,switch 会忽略大小写。输入 XL 时,它会输出 We have S, M and L。

case 也可以是数字。添加 -Wildcard 来使用诸如 "*.txt" 的模式:

switch -Wildcard ("notes.txt") {
    "*.txt" { Write-Output "Text file" }
    "*.csv" { Write-Output "Data file" }
}

这会打印 Text file。

challenge icon

挑战

简单

编写一个小型服务脚本的命令处理程序。

  1. 读取一个带有提示符 Command 的命令。
  2. 对于 start,输出 Starting the service。对于 stop,输出 Stopping the service。对于 status,输出 The service is running。
  3. 对于其他任何输入,输出 Unknown command: ,后跟输入的命令内容。

命令匹配不区分大小写,因此 STOP 的作用与 stop 相同。当输入为 STOP 时,你的脚本输出:

Command: STOP
Stopping the service

当输入为 restart 时,第二行为 Unknown command: restart。

亲手试试

$cmd = Read-Host "Command"
# 使用 switch 处理 start、stop、status 和其他任何情况
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

PowerShell 基础中的所有课