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。
挑战
简单编写一个小型服务脚本的命令处理程序。
- 读取一个带有提示符
Command的命令。 - 对于
start,输出Starting the service。对于stop,输出Stopping the service。对于status,输出The service is running。 - 对于其他任何输入,输出
Unknown command:,后跟输入的命令内容。
命令匹配不区分大小写,因此 STOP 的作用与 stop 相同。当输入为 STOP 时,你的脚本输出:
Command: STOP
Stopping the service当输入为 restart 时,第二行为 Unknown command: restart。
亲手试试
$cmd = Read-Host "Command"
# 使用 switch 处理 start、stop、status 和其他任何情况
这节课包含一个小测验。开始学习即可作答,并记录你的进度。