The Null coalescing operators were introduced in PowerShell v7 preview 5. last time you saw how to use Null coalescing with variables. You can also use Null coalescing with Object properties.
Let’s first create an object.
PS> $prop = @{Nullprop = $null; NonNullProp = ‘something’}
PS> $obj = New-Object -TypeName PSobject -Property $prop
Yes, I know there other ways but I prefer this approach.
Using the Null coalescing operator
PS> $obj.NonNullProp ?? ‘is null’
something
PS> $obj.NullProp ?? ‘is null’
is null
is very similar to working with variables.
The Null coalescing assignment operator
PS> $obj.NonNullProp ??= ‘is null’
PS> $obj.NullProp ??= ‘is null’
PS> $obj | Format-List
NonNullProp : something
Nullprop : is null
If the property is non-null nothing happens. If the property is null the property is assigned the value on the right hand side of the operator.
To my mind the Null coalescing operator and the Ternary operator introduced in PowerShell v7 preview 4 fall into the same category of great if you need to perform these operations on a regular basis and are used to thinking in these terms but otherwise not something to bother with. We’ve managed to survive through 6 versions of PowerShell without them and I don’t see them as a great step forward or particularly useful for IT administrators.