Skip to content

Latest commit

 

History

History

Missing-ternary-operator

Missing ternary operator

PowerShell v7.preview.4 introduced the ternary operator. Older versions do not have it but workarounds exist.

Workaround 1: if/else statement

The well known workaround is

$result = if ($condition) {$data1} else {$data2}

It will do in most cases. But there are some drawbacks.

if/else may lose the original data type, see the tests and Unrolled-collections.

if/else is a statement, not an expression, see Statements-are-not-expressions. Although it can be assigned to a variable, it cannot be used directly as a part of another expression. In this case the subexpression $(if ...) must be used.

Workaround 2: array/index expression

Yet another possible workaround is

$result = ($data1, $data2)[!$condition]

It is not pretty perhaps but it preserves the original data type and it is an expression, so that it can be used as a part of another expression directly.

Scripts


  • Microsoft Connect 53059