This post is all about using coalescing operators in PowerShell 7. If you’re not using it yet, I highly recommend giving it a try! You can install it side-by-side with Windows PowerShell 5.1 (or earlier), so nothing breaks—and it comes with a bunch of great improvements.

Null-Coalescing Operator (??)

With this operator, you don’t need to write if-else statements just to check if a value is $null. The ?? operator checks if the value on the left is not $null. If it isn’t, it uses that value. If it is $null, it falls back to the value on the right.

## With Values
$variable01 = $null ?? "Hello World!"
$variable01
# Output: Hello World!

## With Functions
Function Get-NullValue {
    return $null
}

$variable02 = Get-NullValue ?? (Get-Uptime).ToString() ?? "None"
$variable02
# Output: 06:25:36


Null-Coalescing Assignment Operator (??=)

The ??= operator is a handy shortcut. It checks if the variable on the left is $null, and if it is, it assigns it the value on the right.

$MovieCharacter = "Jon Snow"
$MovieCharacter ??= "Luke Skywalker"

$MovieCharacter
# Output: Jon Snow

Wrapping Up

The ?? and ??= operators are small but powerful tools that can make your PowerShell scripts cleaner, safer, and easier to read. They help you avoid repetitive null checks and make your code more resilient—especially when dealing with optional inputs, config values, or external data.

Give them a try in your next script—you might be surprised how much cleaner your code looks!

Leave a Reply

Your email address will not be published. Required fields are marked *