今天我们来看一下 powershell 中的另一种逻辑判断 switch.
switch 语法:
switch($value)
{
{test_expression} {doing}
{test_expression} {doing}
......
}
在多分支条件逻辑判断的时候,我们除了可以使用 if...elseif...else 外,我们还可以使用 switch。下面我们来看一个一下,怎么通过通过 switch 的方式来处理多个逻辑判断。
我们前面的 if 的示例:
$height = read-Host "Please eenter your height"
$weight = read-Host "Please eenter your weight"
$bmi = $weight/([math]::pow($height,2))
Write-Host "BMI is $bmi."
if ( $bmi -lt 18.5)
{
Write-Host "You are too thin."
}
elseif (( $bmi -gt 18.5) -and ($bmi -lt 23.9))
{
Write-Host "Your are healthy."
}
elseif (( $bmi -gt 24) -and ( $bmi -lt 27))
{
Write-Host "Your are a little fat."
}
elseif ( $bmi -gt 32)
{
Write-Host "You are too fat."
}
else
{
Write-Host "error."
}
通过 switch 来写:
$height = read-Host "Please eenter your height"
$weight = read-Host "Please eenter your weight"
$bmi = $weight/([math]::pow($height,2))
Write-Host "BMI is $bmi."
switch ($bmi)
{
{ $bmi -lt 18.5 } { Write-Host "You are too thin." }
{ ( $bmi -gt 18.5) -and ($bmi -lt 23.9) } { Write-Host "Your are healthy." }
{ ( $bmi -gt 24) -and ( $bmi -lt 27) } { Write-Host "Your are a little fat." }
{ $bmi -gt 32 } { Write-Host "You are too fat." }
default { Write-Host "error." }
}
运行结果: