PowerShell live documentation

The null-coalescing operator

Double evaluation of first argument

The null-coalescing operator was introduced in PowerShell 7. In versions 7.0.0 and 7.0.1, however, the first argument of the operator is evaluated twice if it's not null.

Notice that "ran func" is only printed out once even though the counter is incremented twice. This is because the actual output of the function is only used once, while any side effects such as incrementing a counter or calling Write-Host would occur twice.

  1. $global:counter = 0
  2. function func {
  3.     $global:counter += 1
  4.     Write-Output 'ran func'
  5. }
  6. (func) ?? 'func returned null'
  7. Write-Output "Counter: $global:counter"
Stdout
ran func
Counter: 2
ran func
Counter: 1

If the first argument is null, it's only evaluated once.

  1. $global:counter = 0
  2. function func {
  3.     $global:counter += 1
  4. }
  5. (func) ?? 'func returned null'
  6. Write-Output "Counter: $global:counter"
Stdout
func returned null
Counter: 1