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

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

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

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


当前回答

我最近改进了(打开PullRequest) PoweShell库'Pscx'中的三元条件和空合并操作符 请看我的解决办法。

我的github主题分支:UtilityModule_Invoke-Operators

功能:

Invoke-Ternary
Invoke-TernaryAsPipe
Invoke-NullCoalescing
NullCoalescingAsPipe

别名

Set-Alias :?:   Pscx\Invoke-Ternary                     -Description "PSCX alias"
Set-Alias ?:    Pscx\Invoke-TernaryAsPipe               -Description "PSCX alias"
Set-Alias :??   Pscx\Invoke-NullCoalescing              -Description "PSCX alias"
Set-Alias ??    Pscx\Invoke-NullCoalescingAsPipe        -Description "PSCX alias"

使用

<condition_expression> |?: <true_expression> <false_expression>

<variable_expression> |?? <alternate_expression>

作为表达式,你可以传递: $null,一个文字,一个变量,一个“外部”表达式($b -eq 4)或一个脚本块{$b -eq 4} 如果变量表达式中的变量为$null或不存在,则计算备用表达式作为输出。

其他回答

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

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

参见:PowerShell内联If (IIf)

下面是另一种自定义函数方法:

function Test-TernaryOperatorCondition {
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline = $true, Mandatory = $true)]
        [bool]$ConditionResult
        ,
        [Parameter(Mandatory = $true, Position = 0)]
        [PSObject]$ValueIfTrue
        ,
        [Parameter(Mandatory = $true, Position = 1)]
        [ValidateSet(':')]
        [char]$Colon
        ,
        [Parameter(Mandatory = $true, Position = 2)]
        [PSObject]$ValueIfFalse
    )
    process {
        if ($ConditionResult) {
            $ValueIfTrue
        }
        else {
            $ValueIfFalse
        }
    }
}
set-alias -Name '???' -Value 'Test-TernaryOperatorCondition'

例子

1 -eq 1 |??? 'match' : 'nomatch'
1 -eq 2 |??? 'match' : 'nomatch'

差异的解释

Why is it 3 question marks instead of 1? The ? character is already an alias for Where-Object. ?? is used in other languages as a null coalescing operator, and I wanted to avoid confusion. Why do we need the pipe before the command? Since I'm utilising the pipeline to evaluate this, we still need this character to pipe the condition into our function What happens if I pass in an array? We get a result for each value; i.e. -2..2 |??? 'match' : 'nomatch' gives: match, match, nomatch, match, match (i.e. since any non-zero int evaluates to true; whilst zero evaluates to false). If you don't want that, convert the array to a bool; ([bool](-2..2)) |??? 'match' : 'nomatch' (or simply: [bool](-2..2) |??? 'match' : 'nomatch')

Powershell 7有这个功能。

PS C:\Users\js> 0 ? 'yes' : 'no'
no
PS C:\Users\js> 1 ? 'yes' : 'no'
yes

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的构造是:

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