The Null-Coalescing Operator


A closer look at the null-coalescing operator and how it can help us in writing smarter, more concise scripts.

Today we take a closer look at the null-coalescing operator and how it can help us in writing smarter, more concise scripts.

PS> $userDate ?? (Get-Date -Format "yyyy-MM-dd")
2021-02-14

PS> $userDate = Get-Date -Year 2020 -Format "yyyy-MM-dd"
PS> $userDate ?? (Get-Date -Format "yyyy-MM-dd")
2020-02-14

How it works

We can write some simple code to visualize what the null-coalescing operator is doing

function nullCoalescingOperator ($leftValue, $rightValue) {
    if ($null -eq $leftValue) {
        return $rightValue
    } else {
        return $leftValue
    }
}

Usually we will want to assign the resulting value to a variable.

PS> $userDate = $userDate ?? (Get-Date -Format "yyyy-MM-dd")

For this operation PowerShell implements a nice shortcut, the null-coalescing assignment operator.

PS> $userDate ??= (Get-Date -Format "yyyy-MM-dd")

Where to use it

You can use this in a variety of situations, I mostly use this when I query some external data and cant be sure a field I require is actually present.

$data = Get-FictionalData -Id 1
$data.source ??= "cloud"
$data.type ??= "fictional"

Or when preparing a complex object from values earlier in the code to be send somewhere.

$requestPayload = @{
    name = $name
    source = $source ?? "mysccript-v$scriptVersion"
    creationDate = $date ?? (Get-Date)
}
Send-FictionalData $requestPayload

See also