Ternary operator in PowerShell

后端 未结 13 2095
忘掉有多难
忘掉有多难 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:22

    If you're just looking for a syntactically simple way to assign/return a string or numeric based on a boolean condition, you can use the multiplication operator like this:

    "Condition is "+("true"*$condition)+("false"*!$condition)
    (12.34*$condition)+(56.78*!$condition)
    

    If you're only ever interested in the result when something is true, you can just omit the false part entirely (or vice versa), e.g. a simple scoring system:

    $isTall = $true
    $isDark = $false
    $isHandsome = $true
    
    $score = (2*$isTall)+(4*$isDark)+(10*$isHandsome)
    "Score = $score"
    # or
    # "Score = $((2*$isTall)+(4*$isDark)+(10*$isHandsome))"
    

    Note that the boolean value should not be the leading term in the multiplication, i.e. $condition*"true" etc. won't work.

提交回复
热议问题