Please feel free to provide feedback or file bugs here.

Provide a native ternary operator

It would be very nice and convenient if PowerShell had a native ternary operator like C# does (https://msdn.microsoft.com/en-us/library/zakwfxx4(v=vs.100).aspx).

Basically it would allow you to write a short-hand if-else statement, so instead of having to write:

if ($someBoolCondition)
{
$x = $y.Property1
}
else
{
$x = $y.Property2
}

you could just write:

$x = $someBoolCondition ? $y.Property1 : $y.Property2

This operator is fairly standard in many programming languages, so it would be awesome if PowerShell could come up to speed with it as well. Thanks.

2 votes
Sign in
Check!
(thinking…)
Reset
or sign in with
  • facebook
  • google
    Password icon
    I agree to the terms of service
    Signed in as (Sign out)

    We’ll send you updates on this idea

    Daniel SchroederDaniel Schroeder shared this idea  ·   ·  Flag idea as inappropriate…  ·  Admin →

    2 comments

    Sign in
    Check!
    (thinking…)
    Reset
    or sign in with
    • facebook
    • google
      Password icon
      I agree to the terms of service
      Signed in as (Sign out)
      Submitting...
      • Joakim SvendsenJoakim Svendsen commented  ·   ·  Flag as inappropriate

        That's quite hacky sweet, Tim Curwick, but I'd like operators anyway, like the poster. Maybe ... first thought after like 45 seconds of consideration: $foo = $foo -match 'hy' -IfTrue 'Hi!' -IfFalse 'wat u say?'

        Those names can probably be made a lot more logical or intuitive, I've had some wine since we're about to have a family barbecue, so I might not be thinking as clearly as I am capable of (on rare occasions). Not sure it's even a good idea with new dash operators, but it is flexible and allows for "random names" ... Just a thought.

      • Tim CurwickTim Curwick commented  ·   ·  Flag as inappropriate

        Daniel,

        It isn't exactly what you are looking for, but this syntax works:

        ( "False result", "True result" )[$BoolTest]

        For your example, it would be:

        $x = ( $y.Property2, $y.Property1 )[$someBoolCondition]

        PowerShell converts the boolean to an int32, 1 for $True, 0 for $False, and uses the result to index into the array of choices.

        To use an actual conditional, wrap it in parentheses within the square brackets:

        ( "False result", "True result")[( $A -lt 10 )]

      Feedback and Knowledge Base