If、ElseIf 和 Else
本课属于 Coddy PowerShell 学习旅程的“PowerShell 基础”单元。第 13 课,共 28 课。
if 仅在其条件为 True 时运行一段代码。条件放在圆括号内,代码块放在大括号内:
$battery = [int](Read-Host "Battery")
if ($battery -lt 10) {
Write-Output "Charge now"
} elseif ($battery -lt 50) {
Write-Output "Charge soon"
} else {
Write-Output "Battery is fine"
}PowerShell 从上到下依次测试条件,并运行第一个条件为 True 的代码块,其余代码块会被跳过。当没有任何条件匹配时,会运行 else。当输入为 30 时,这会打印 Battery: 30 和 Charge soon:30 不小于 10,但它小于 50。
因为最先匹配的条件会生效,请将范围最窄的测试放在最前面。你可以有任意数量的 elseif 块,以及最多一个 else。
要连接两个条件,可以使用 -and(两者都必须为 True)或 -or(只需满足其中一个);-not 会将 True 转换为 False:if ($battery -ge 50 -and $battery -lt 80)。
挑战
简单读取摄氏温度值并对其进行描述。
- 使用提示
Temperature读取一个整数。 - 低于 0 时输出
Freezing,0 到 14 时输出Cold,15 到 24 时输出Warm,25 及以上输出Hot。
输入为 14 时,你的脚本会输出:
Temperature: 14
Cold输入为 15 时,第二行为 Warm;输入为 -5 时,第二行为 Freezing。
亲手试试
$t = [int](Read-Host "Temperature")
# 输出 Freezing、Cold、Warm 或 Hot
这节课包含一个小测验。开始学习即可作答,并记录你的进度。