PowerShell and the “missing” ternary operator

tree4

People switching to PowerShell from other languages like JavaScript or C# might be looking for a ternary operator at one point. While there is no built-in ternary operator in PowerShell it is not too hard to come up with something that comes pretty close to it. Let’s look at an example:

filter Get-FourthLetter{
    if ($_.Length -gt 3){
        $_[3]
    }
    else{
        -1
    }
}
'Pete', 'Joe', 'Dirk' | Get-FourthLetter

This defines a (admittedly pretty useless) filter (like a function but with a process block only) to get the fourth letter of any word that is “piped” into the filter, which has more than 4 characters or -1 (in case the word has less than 4 chars). Let’s try to re-write this with “something like” a ternary operator in PowerShell:

filter Get-FourthLetter{
    (-1, $_[3])[$_.Length -gt 3]
}
'Pete', 'Joe', 'Dirk'  | Get-FourthLetter

Here we replace the if/else construct with a simple array construct of the form (FALSEEXPRESSION, TRUEEXPRESSION). The CONDITION part is then used to index into the array by making use of the fact that $true evaluates to 1 and $false to 0 in PowerShell. To increase the “uselessness” factor even further, let’s wrap the “ternary” operator functionality into a more generic filter:

filter ?:($trueExpression, $falseExpression){
    ($falseExpression, $trueExpression)[$_]
}
'Pete', 'Joe', 'Dirk'  | % { ($_.Length -gt 3)  | ?: $_[3] -1 }

I hope this will help anyone that has been desperately searching for a PowerShell ternary operator ;-).

shareThoughts


photo credit: Purple storm. Old Jacarandas avenue in Goodna, near Brisbane via photopin (license)

Advertisements

I'd love to hear what you think

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s