Powershell v7 preview 5 introduces a new experimental feature that supports Null coalescing operators and null coalescing assignment operstors.
As its an experimental feature:
PS> Get-ExperimentalFeature -Name PSCoalescingOperators | Format-List
Name : PSCoalescingOperators
Enabled : False
Source : PSEngine
Description : Support the null coalescing operator and null coalescing assignment operator in PowerShell language
You have to enable it:
PS> Enable-ExperimentalFeature -Name PSCoalescingOperators
WARNING: Enabling and disabling experimental features do not take effect until next start of PowerShell.
And then restart PowerShell.
Create a variable with $null as its value
PS> $nvar = $null
Using the coalescing operator
PS> $nvar ?? ‘is null’
is null
if $nvar is null the string is returned
By contrast a non-null value won’t return the ‘is null’ string
PS> $num = 1
PS> $num ?? ‘is null’
1
PS> $str = ‘aaa’
PS> $str ?? ‘is null’
aaa
The ?? operator checks the left hand side to be null or undefined and returns the value of right hand side if null, else return the value of left hand side.
The coalescing operator is equivalent to
PS> if ($nvar -eq $null) {‘is null’}else {$nvar}
is null
The Null assignment operator ??= operator check the left hand side to be null or undefined and assigns the value of right hand side if null, else the value of left hand side is not changed.
PS> $date1 = Get-Date
PS> $date2 ??= Get-Date
PS> $date1
25 October 2019 21:19:48
PS> $date2
25 October 2019 21:22:03
Using the null coalescing assignment operator is equivalent to
PS> if ($date2 -eq $null) {$date2 = Get-Date}
PS> $date2
25 October 2019 21:24:09