Ternary operator in PowerShell

后端 未结 13 2112
忘掉有多难
忘掉有多难 2020-11-28 03:56

From what I know, PowerShell doesn\'t seem to have a built-in expression for the so-called ternary operator.

For example, in the C language, which supports the terna

13条回答
  •  星月不相逢
    2020-11-28 04:18

    Here's an alternative custom function approach:

    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'
    

    Example

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

    Differences Explained

    • 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')

提交回复
热议问题