PowerShell 中的三元运算符是如何工作的?


PowerShell 中的三元运算符是在 PowerShell 版本 7.0 中引入的。三元运算符具有“?”(问号)符号,其语法为:

[Condition] ? (output if True) : (output if false)

三元运算符的左侧为条件,右侧为基于条件语句的输出。条件的输出采用布尔形式,如果条件为真,则执行真块;如果条件为假,则执行假块。例如:

示例

$a = 5; $b = 6
($a -gt $b) ? "True" : "false"

输出

false

正如您所看到的,值 5 小于 6,因此上述条件为假并执行了第二个块。您还可以修改语句,如下所示:

($a -gt $b) ? ("$a is greater than $b") : ("$a is less than $b")

输出

5 is less than 6

您可以看到,代码量减少了一行,如果我们使用 if/else 条件写成代码,则会出现以下情况:

$a = 5; $b = 6

if($a -gt $b){"$a is greater than $b"}
else{"$b is greater than $a"}

因此,使用三元运算符似乎很简单。您还可以在运算符左侧使用返回布尔值的 cmdlet。

示例

(Test-Connection google.com -Count 2 -Quiet) ? "Google.Com server is reachable" : "Google.Com server is unrechable"

输出

Google.Com server is reachable

尽量使这个三元运算符尽可能简单。如果在脚本编写目的中使用了三元运算符的右侧部分,它并不总是能正常工作。

更新于:2020-11-11

5K+ 浏览

开启你的 生涯

通过完成课程获得认证

入门
广告
© . All rights reserved.