Ternary operator in PowerShell

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

    PowerShell currently doesn't have a native Inline If (or ternary If) but you could consider to use the custom cmdlet:

    IIf <condition> <condition-is-true> <condition-is-false>
    See: PowerShell Inline If (IIf)

    0 讨论(0)
  • 2020-11-28 04:30

    The closest PowerShell construct I've been able to come up with to emulate that is:

    @({'condition is false'},{'condition is true'})[$condition]
    
    0 讨论(0)
  • 2020-11-28 04:30

    Try powershell's switch statement as an alternative, especially for variable assignment - multiple lines, but readable.

    Example,

    $WinVer = switch ( Test-Path $Env:windir\SysWOW64 ) {
      $true    { "64-bit" }
      $false   { "32-bit" }
    }
    "This version of Windows is $WinVer"
    
    0 讨论(0)
  • 2020-11-28 04:31

    Since a ternary operator is usually used when assigning value, it should return a value. This is the way that can work:

    $var=@("value if false","value if true")[[byte](condition)]
    

    Stupid, but working. Also this construction can be used to quickly turn an int into another value, just add array elements and specify an expression that returns 0-based non-negative values.

    0 讨论(0)
  • 2020-11-28 04:32

    Since I have used this many times already and didn't see it listed here, I'll add my piece :

    $var = @{$true="this is true";$false="this is false"}[1 -eq 1]

    ugliest of all !

    kinda source

    0 讨论(0)
  • 2020-11-28 04:34

    As of PowerShell version 7, the ternary operator is built into PowerShell.

    1 -gt 2 ? "Yes" : "No"
    # Returns "No"
    
    1 -gt 2 ? 'Yes' : $null
    # Get a $null response for false-y return value
    
    0 讨论(0)
提交回复
热议问题