PowerShell中的三元运算符 [英] Ternary operator in PowerShell
本文介绍了PowerShell中的三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
据我所知,PowerShell似乎没有所谓的三元运算符<的内置表达式/ a>。
From what I know, PowerShell doesn't seem to have a built-in expression for the so-called ternary operator.
例如,在支持三元运算符的C语言中,我可以这样写:
For example, in the C language, which supports the ternary operator, I could write something like:
<condition> ? <condition-is-true> : <condition-is-false>;
如果在PowerShell中确实不存在,那是最好的方法(即易于阅读)并保持)以达到相同的结果?
If that doesn't really exist in PowerShell, what would be the best way (i.e. easy to read and to maintain) to accomplish the same result?
推荐答案
$result = If ($condition) {"true"} Else {"false"}
其他所有事情都是附带的复杂性,因此
Everything else is incidental complexity and thus to be avoided.
要用于表达式或表达式(不仅仅是赋值),请将其包装在 $()
中,因此:
For use in or as an expression, not just an assignment, wrap it in $()
, thus:
write-host $(If ($condition) {"true"} Else {"false"})
这篇关于PowerShell中的三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文