PowerShell Hacks: Ternarys and Null-coalescing operators
It took me a long time to actually start using PowerShell for my daily scripting tasks, mainly beacuse I was so damn good at CMD shell scripts, and it was such a hassle to learn to do everything differently.
However, as I worked more with PowerShell, I got to like it a lot, and now use it for virtually all my automation needs.
Daily dose of what’s wrong
A couple of big gripes come from the lack of a decent ternary operator in the language–which is a very terse way of cramming a whole if/else statement into a single expression:
A C# Example:
That time when someone tried to fix it with some duck-tape
Sadly, there exists no comparable feature in PowerShell. Searching the internets, I found an attempt to make something that is kinda the same:
Which lets one use a construct that looks like this:
sigh … I’ll give high marks for terse, but … not really the same readability as a C-style ternary.
Hack like nobody is watching
I have made (in my ever-so-humble opinion) a far smarter way to accomplish the support of a Ternary in PowerShell.
Let’s take a look at some examples, and I’ll show the code to accomplish this at the end.
Simple, straightforward ternary
How about if it’s false
More fun
The other thing that’s missing from a PowerShell is a null-coalescing operator. In a c# example:
Which offers a clean, tight and simple way of saying if the answer is null, then use this answer instead.
Maybe we can do the samething in PowerShell?
How much would you pay for a null-coalescing operator like C# ?
Of course, it still thinks like powershell so 0, false and $null are all still ‘negative’
And regular numbers work nice:
Let’s try some more complicated examples
A slight variation
What does this one do?
We can drop the pretenses; you should have a clue by now.
A couple more bits of fun:
Taking a peek behind the curtain
The ever-so-clever PowerShell enthusiasts will have probably guessed why this works.
It turns out that the power of PowerShell’s aliases is actually quite amazing, and when combined with a means
of evaluating a parameter-regardless if it’s an scriptblock or just a value
made it pretty simple to ‘extend’ assignment with an extra equal sign =
Now, go forth, and bring terseness and compaction to your scripts!