Ternary statements can be very useful but difficult to read. Many blue moons ago, I used to write a lot of Java, which has a ternary statement just like C:
x = (condition) ? 1 : 0;
It is a short and concise way to have a condition if it is a matter of setting a simple value, but even in that case, if you are unfamiliar with what a ternary is then it is next to being unreadable magic code (like a lot of Perl that I have seen written).
I was watching a video on Python and saw a very clean looking ternary:
x = 1 if condition else 0
That is very straight forward and relatively easy to understand. Even if you do not know what a ternary is, you can likely understand that this is a conditional statement.
I have always wanted a ternary in PowerShell because I like to reduce my lines of code, but I never want to make it ugly or unreadable, so this is out:
$x = If ($condition) {1} Else {0}
It is just too much to cram into one line because chances are, it will be a slightly more complicated bit of code than that very simple example.
Then, I came across this:
$x = @{$True=1;$False=0}[($condition)]
It isn’t exactly cleaner, but it may be clearer as a ternary. It is a longer bit of code for the same task, too.
What do you think?
EDIT: Here is some discussion about a filter method
$x = ?: {$condition} {1} {2}
One thought on “PowerShell Ternary Statement”