Using ternary operator in PowerShell 7

Developers for high level programming language have been familiar with the ternary operator ? : which goes like: <condition> ? <if-true> : <if-false>. It makes for more concise code in case of simple conditions and expressions. With PowerShell 7, this operator has been available and we can utilize the same.

The condition-expression is always evaluated and its result is converted to a Boolean to determine which branch is evaluated next:

  • The <if-true> expression is executed if the <condition> expression is true
  • The <if-false> expression is executed if the <condition> expression is false

Before PowerShell 7

One can achieve the above behavior by using if..else conditional block. For example, consider below code:

#region - Before PS7
$process_status = Get-Process -name notepad++ -ErrorAction SilentlyContinue
if($process_status){
    $process_status | Stop-Process -Confirm:$false
}
else{
    Write-Host "notepad++ is not running"
}
#endregion

After PowerShell 7

We can re-write above code as below in PowerShell 7 or later:

#region - After PS7
(Get-Process -name notepad++ -ErrorAction SilentlyContinue) ? ($process_status | Stop-Process -Confirm:$false) : (Write-Host "notepad++ is not running")
#endregion

Note that if our expressions are complex, we need to encapsulate them within parenthesis operator (). Also, if the condition before the ? results in null, its evaluated to $false.

Also, to be noted that the question mark and colon are compatible with line continuation. So above code can also be written as:

(Get-Process -name notepad++ -ErrorAction SilentlyContinue) ? 
($process_status | Stop-Process -Confirm:$false) : 
(Write-Host "notepad++ is not running")

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s