Using Null Conditional Assignment in PowerShell 7

PowerShell 7 introduces few new operators to help sysadmins and dev alike, to work with null values. One of these operator is null conditional assignment operator (??=). Using this operator, allows us to write more cleaner and concise code. In this blog post, we’ll learn about the null conditional assignment operator.

Life Before PowerShell 7

Before PowerShell 7, we needed to use an if condition to check if the variable is null or not using $null operator and then perform the assignment, if that’s the case. For example, consider below code:

$my_var
if($null -eq $my_var){
    $my_var = 5
}
Write-Host $my_var

Above code will output 5.

Life After PowerShell 7

Null Conditional Assignment Operator ??= in PowerShell assigns the value of the right-hand side operand to the left-hand operand only if the left-hand operand value is null. This operator doesn’t evaluate the right-hand side operand if the left-hand side operand is Null. This allows us to write more cleaner and concise code.

For example, above code can be re-written as below:

$my_var ??= 5

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