Powershell: another alternative to ternary operator

February 23, 2012

...

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 🙂.


Profile picture

Written by Vidar Kongsli who is a software professional living in Oslo, Norway. Works as a consultant, system architect and developer at Bredvid. You should follow him on Twitter