据我所知,PowerShell似乎没有用于所谓三元运算符的内置表达式。

例如,在支持三元操作符的C语言中,我可以这样写:

<condition> ? <condition-is-true> : <condition-is-false>;

如果PowerShell中没有这样的功能,那么要达到同样的效果(即易于阅读和维护),最好的方法是什么?


当前回答

PowerShell目前没有一个本地内联If(或三元If),但你可以考虑使用自定义cmdlet:

IIf <condition> <condition-is-true> <condition-is-false>

参见:PowerShell内联If (IIf)

其他回答

根据这篇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版本7开始,三元运算符被内置到PowerShell中。

1 -gt 2 ? "Yes" : "No"
# Returns "No"

1 -gt 2 ? 'Yes' : $null
# Get a $null response for false-y return value

我能够想出的最接近PowerShell的构造是:

@({'condition is false'},{'condition is true'})[$condition]

PowerShell目前没有一个本地内联If(或三元If),但你可以考虑使用自定义cmdlet:

IIf <condition> <condition-is-true> <condition-is-false>

参见:PowerShell内联If (IIf)

$result = If ($condition) {"true"} Else {"false"}

为了在表达式中或作为表达式使用,而不仅仅是赋值,将它包装在$()中,这样:

write-host  $(If ($condition) {"true"} Else {"false"})