PowerShell inline If (IIf)

后端 未结 7 1977
独厮守ぢ
独厮守ぢ 2020-12-07 16:24

How do I create an a statement with an inline If (IIf, see also: Immediate if or ternary If) in PowerShell?

If you also think that this should be a native Po

7条回答
  •  伪装坚强ぢ
    2020-12-07 17:18

    From blog post DIY: Ternary operator:

    Relevant code:
    # —————————————————————————
    # Name:   Invoke-Ternary
    # Alias:  ?:
    # Author: Karl Prosser
    # Desc:   Similar to the C# ? : operator e.g. 
    #            _name = (value != null) ? String.Empty : value;
    # Usage:  1..10 | ?: {$_ -gt 5} {“Greater than 5;$_} {“Not greater than 5”;$_}
    # —————————————————————————
    set-alias ?: Invoke-Ternary -Option AllScope -Description “PSCX filter alias”
    filter Invoke-Ternary ([scriptblock]$decider, [scriptblock]$ifTrue, [scriptblock]$ifFalse) 
    {
       if (&$decider) { 
          &$ifTrue
       } else { 
          &$ifFalse 
       }
    }
    

    And then you can use that like this:

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

    This is the closest variant I have seen so far.

提交回复
热议问题