Ternary operator in PowerShell

后端 未结 13 2114
忘掉有多难
忘掉有多难 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条回答
  •  猫巷女王i
    2020-11-28 04:20

    Per this PowerShell blog post, you can create an alias to define a ?: 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 
       }
    }
    

    Use it like this:

    $total = ($quantity * $price ) * (?:  {$quantity -le 10} {.9} {.75})
    

提交回复
热议问题