Using the conditional ternary operator for simplified if/else syntax in PowerShell 7

The conditional ternary operator is a feature added to PowerShell in version 7. You can use it as a simplified version of if/else.

The syntax for the ternary operator takes three operands:

  • A condition to evaluate followed by a question mark (?).
  • An expression to execute if the condition is true, followed by a colon (:).
  • And finally, an expression to execute if the condition is false.
<condition-to-evaluate> ? <expression-to-execute-if-true> : <expression-to-execute-if-false>

The examples in this blog article were tested using Windows 11 version 21H2, PowerShell version 7.2.4, and the Az PowerShell module version 8.0.0.

The following example returns true if resources exist in the specified Azure resource group. It returns false if no resources exist in the resource group.

$resourceGroup = '<resource-group-name>'
(Get-AzResource -ResourceGroupName $resourceGroup) ? $true : $false

ternary-operator-syntax1a.jpg

Variables set inside the parentheses can be used for logic in the true or false portion of the syntax.

(Get-AzResource -ResourceGroupName $resourceGroup -OutVariable results) ? $results.ResourceType : $false

ternary-operator-syntax2a.jpg

You can line break after the question mark (?) because PowerShell knows the command’s syntax isn’t complete:

(Get-AzResource -ResourceGroupName $resourceGroup -OutVariable results) ?
$results.ResourceType : $false

ternary-operator-syntax3a.jpg

You can also line break after the colon (:):

(Get-AzResource -ResourceGroupName $resourceGroup -OutVariable results) ?
$results.ResourceType :
$false

ternary-operator-syntax4a.jpg

The line breaks shown in the previous two examples aren’t mentioned in the official Microsoft docs for using the ternary operator syntax in PowerShell.

Caution: Line breaks may not be supported. Use them at your own risk.

I’ve removed the only resource from the specified resource group. The same command now returns false.

(Get-AzResource -ResourceGroupName $resourceGroup -OutVariable results) ? $results.ResourceType : $false

ternary-operator-syntax5a.jpg

The question mark (?) being used for ternary operator syntax and as an alias for Where-Object is one more reason you shouldn’t use aliases in any PowerShell code you save or share.

ยต