Powershell: another alternative to ternary operator

In C# (as well as in Java and C++), you can use the ternary operator (?:) for a shorthand notation for conditionally assigning a value:

var index = (a == "a") ? 1 : 2;

In Powershell, such an operator is (to my knowledge) not available. One solution is described here. As an alternative without having to create a function and alias, I suggest:

$index = @{$true=1;$false=2}[$a -eq 'a']

Mmmmm, one-liner FTW :)

Share
  • Slava Gorbunov

    That worked for me. Thanks a lot. :)

  • ds

    Handy tip – cheers :)

  • Robbie Khaddaj

    Awesome! Shortens my code by a few lines :)

  • Sd

    Awesome

  • http://tahirhassan.myopenid.com/ tahirhassan

    It’s worth mentioning that in powershell 2 you can write:

    $index = switch ($a) { “a” { 1 } default { 2 } }

  • http://tahirhassan.myopenid.com/ tahirhassan

    Also the following syntax (also powershell 2) works:

    $index = if ($a -eq “a”) { 1 } else { 2 }

    -Tahir

  • http://www.kongsli.net/nblog/ Vidar Kongsli

    Excellent. I did not know that blocks have a return value. Cleaner my than original suggestion…