From what I know, PowerShell doesn't seem to have a built-in expression for the so-called ternary operator.
For example, in the C language, which supports the ternary operator, I could write something like:
<condition> ? <condition-is-true> : <condition-is-false>;
If that doesn't really exist in PowerShell, what would be the best way (i.e. easy to read and to maintain) to accomplish the same result?
Since I have used this many times already and didn't see it listed here, I'll add my piece :
$var = @{$true="this is true";$false="this is false"}[1 -eq 1]
ugliest of all !
kinda source
The closest PowerShell construct I've been able to come up with to emulate that is:
Try powershell's switch statement as an alternative, especially for variable assignment - multiple lines, but readable.
Example,
Everything else is incidental complexity and thus to be avoided.
For use in or as an expression, not just an assignment, wrap it in
$()
, thus:I've recently improved (open PullRequest) the ternary conditional and null-coalescing operators in the PoweShell lib 'Pscx'
Pls have a look for my solution.
My github topic branch: UtilityModule_Invoke-Operators
Functions:
Aliases
Usage
As expression you can pass:
$null, a literal, a variable, an 'external' expression ($b -eq 4) or a scriptblock {$b -eq 4}
If a variable in the variable expression is $null or not existing, the alternate expression is evaluated as output.
I too, looked for a better answer, and while the solution in Edward's post is "ok", I came up with a far more natural solution in this blog post
Short and sweet:
Which makes it easy to do stuff like (more examples in blog post):