Ternary operator in PowerShell

mguassa picture mguassa · Jul 10, 2015 · Viewed 130.4k times · Source

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?

Answer

fbehrens picture fbehrens · Dec 16, 2015
$result = If ($condition) {"true"} Else {"false"}

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:

write-host  $(If ($condition) {"true"} Else {"false"})