Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example of PowerShell Switch judgment statement

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/03 Report--

示例一,在if else语句中,如果没有匹配的条件,可以使用else处理,同样在switch语句中,如果case中没有条件匹配,可以使用关键字default处理

$temperature = 20switch($temperature){ {$_ -lt 32} {"below freezing";break} {$_ -le 50} {"cold";break} {$_ -le 70} {"hot"} default {"hot"}}

switch是多路分支,也可用于循环处理

将foreach循环转换为switch循环

$nums = 10..7switch($nums){default{"n=$_"}}

结果

n=10n=9n=8n=7

有时候循环还需要加条件判断,例如foreach可能还要配合if语句,这里面可以使用switch一次性完成

示例二

$nums = 10..7switch($nums){{($_ % 2) -eq 0}{"$_ 偶数"}#%代表的是取余运算,10%2的余数是0,偶数{($_ % 2) -ne 0}{"$_ 基数"}}

示例三

switch($value=Read-Host "输入取值"){1{"Beijing"}2{"shanghai"}3{"guangzhou"}4{"shenzhen"}}

如果碰到匹配条件时只处理一次,可以使用break

$value=99 # 使用 Switch 测试取值范围 switch($value) { {$_ -lt 5 } { "小于5"; break} {$_ -gt 0 } { "大于0"; break} {$_ -lt 100} { "小于100"; break} Default {"没有匹配条件"} }

您也可以关注下方的微信公众号获取更多资讯

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report