iT邦幫忙

2021 iThome 鐵人賽

DAY 8
0
自我挑戰組

Powershell 入门系列 第 8

Powershell 入门之逻辑判断(下)

今天我们来看一下 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." }
}

运行结果:
https://ithelp.ithome.com.tw/upload/images/20210922/20099494dwNIjDs4Kg.png


上一篇
Powershell 入门之逻辑判断(上)
下一篇
Powershell 入门之循环(上)
系列文
Powershell 入门21
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
雷N
iT邦研究生 1 級 ‧ 2021-09-22 00:12:11

0.0

我要留言

立即登入留言