据我所知,PowerShell似乎没有用于所谓三元运算符的内置表达式。
例如,在支持三元操作符的C语言中,我可以这样写:
<condition> ? <condition-is-true> : <condition-is-false>;
如果PowerShell中没有这样的功能,那么要达到同样的效果(即易于阅读和维护),最好的方法是什么?
据我所知,PowerShell似乎没有用于所谓三元运算符的内置表达式。
例如,在支持三元操作符的C语言中,我可以这样写:
<condition> ? <condition-is-true> : <condition-is-false>;
如果PowerShell中没有这样的功能,那么要达到同样的效果(即易于阅读和维护),最好的方法是什么?
当前回答
Powershell 7有这个功能。
PS C:\Users\js> 0 ? 'yes' : 'no'
no
PS C:\Users\js> 1 ? 'yes' : 'no'
yes
其他回答
根据这篇PowerShell博客文章,你可以创建一个别名来定义?:operator:
set-alias ?: Invoke-Ternary -Option AllScope -Description "PSCX filter alias"
filter Invoke-Ternary ([scriptblock]$decider, [scriptblock]$ifTrue, [scriptblock]$ifFalse)
{
if (&$decider) {
&$ifTrue
} else {
&$ifFalse
}
}
像这样使用它:
$total = ($quantity * $price ) * (?: {$quantity -le 10} {.9} {.75})
我能够想出的最接近PowerShell的构造是:
@({'condition is false'},{'condition is true'})[$condition]
PowerShell中的三元运算符是在PowerShell version7.0中引入的。
[Condition] ? (output if True) : (output if False)
例01
$a = 5; $b = 6
($a -gt $b) ? "True" : "False"
输出
False
例子02
($a -gt $b) ? ("$a is greater than $b") : ("$a is less than $b")
输出
5 is less than 6
更多的信息 https://www.tutorialspoint.com/how-ternary-operator-in-powershell-works
PowerShell目前没有一个本地内联If(或三元If),但你可以考虑使用自定义cmdlet:
IIf <condition> <condition-is-true> <condition-is-false>
参见:PowerShell内联If (IIf)
由于三元操作符通常在赋值时使用,因此它应该返回一个值。这是可行的方法:
$var=@("value if false","value if true")[[byte](condition)]
愚蠢,但有效。此外,这种结构可以用于快速将int转换为另一个值,只需添加数组元素并指定一个返回基于0的非负值的表达式。