Null Coalescing Operator in PowerShell

Introduction

Null coalescing is a powerful feature in PowerShell that helps simplify scripts by providing a way to assign default values to variables when left-hand operand is null. In this article, we will show you how to use null coalescing operator in PowerShell.

Without Using Null Coalescing Operator

The null coalescing operator is useful if we want to assign default value to a variable when this variable is null and depends on another variable.

Suppose we have following script where variable $varB depends on whether variable $varA is null or not. Without null coalescing operator, we have to use if-else syntax.

In real world context, variable $varA typically comes from somewhere that precedes the code. It can be null or not. For the sake of brevity, we hard code variable $varA to be null.


$varA = $null
if ($null -eq $varA) {
    $varB = 'Default value'
} else {
    $varB = $varA
}

Write-Host $varB

The output will be as follows:


Default value

Even though above script works well, we can make it simple using null coalescing operator (??).

After Using Null Coalescing Operator

With null coalescing operator ??, previous script can be simplified as follows:


$varA = $null
$varB = $varA ?? 'Default value'
Write-Host $varB

The output will be the same as in previous example.


Default value

If value is supplied for variable $varA, then this value will be used and assigned to variable $varB.


$varA = 'Hello World'
$varB = $varA ?? 'Default value'
Write-Host $varB

The output will be as follows:


Hello World

Conclusion

The null coalescing operator ?? is a useful feature to simplify our code. It makes our code more readable by reducing the number of conditional branching. Additionally, using this ?? operator can help reduce errors by ensuring that variables always contain valid values before executing code blocks associated with them, which can help make debugging easier should something go wrong during execution time.