Powershell 7+

Powershell 7 introduces native null coalescing, null conditional assignment, and ternary operators in Powershell.

Null Coalescing

$null ?? 100    # Result is 100

"Evaluated" ?? (Expensive-Operation "Not Evaluated")    # Right side here is not evaluated

Null Conditional Assignment

null
$x ??= 100    # $x is now 100
$x ??= 200    # $x remains 100

Ternary Operator

$true  ? "this value returned" : "this expression not evaluated"
$false ? "this expression not evaluated" : "this value returned"

Previous Versions:

No need for the Powershell Community Extensions, you can use the standard Powershell if statements as an expression:

variable = if (condition) { expr1 } else { expr2 }

So to the replacements for your first C# expression of:

var s = myval ?? "new value";

becomes one of the following (depending on preference):

myval -eq $null) { "new value" } else { $myval }
myval -ne $null) { $myval } else { "new value" }

or depending on what $myval might contain you could use:

myval) { $myval } else { "new value" }

and the second C# expression maps in a similar way:

var x = myval == null ? "" : otherval;

becomes

myval -eq $null) { "" } else { $otherval }

Now to be fair, these aren't very snappy, and nowhere near as comfortable to use as the C# forms.

You might also consider wrapping it in a very simple function to make things more readable:

function Coalesce(b) { if (null) { $a } else { $b } }

$s = Coalesce $myval "new value"

or possibly as, IfNull:

function IfNull(b, $c) { if ($a -eq $null) { $b } else { $c } }

$s = IfNull $myval "new value" $myval
$x = IfNull $myval "" $otherval

As you can see a very simple function can give you quite a bit of freedom of syntax.

UPDATE: One extra option to consider in the mix is a more generic IsTrue function:

function IfTrue(b, $c) { if ($a) { $b } else { $c } }

$x = IfTrue ($myval -eq $null) "" $otherval

Then combine that is Powershell's ability to declare aliases that look a bit like operators, you end up with:

New-Alias "??" Coalesce

myval "new value"

New-Alias "?:" IfTrue

q -eq "meaning of life") 42 $otherval

Clearly this isn't going to be to everyone's taste, but may be what you're looking for.

As Thomas notes, one other subtle difference between the C# version and the above is that C# performs short-circuiting of the arguments, but the Powershell versions involving functions/aliases will always evaluate all arguments. If this is a problem, use the if expression form.

Answer from StephenD on Stack Overflow
Top answer
1 of 16
246

Powershell 7+

Powershell 7 introduces native null coalescing, null conditional assignment, and ternary operators in Powershell.

Null Coalescing

$null ?? 100    # Result is 100

"Evaluated" ?? (Expensive-Operation "Not Evaluated")    # Right side here is not evaluated

Null Conditional Assignment

null
$x ??= 100    # $x is now 100
$x ??= 200    # $x remains 100

Ternary Operator

$true  ? "this value returned" : "this expression not evaluated"
$false ? "this expression not evaluated" : "this value returned"

Previous Versions:

No need for the Powershell Community Extensions, you can use the standard Powershell if statements as an expression:

variable = if (condition) { expr1 } else { expr2 }

So to the replacements for your first C# expression of:

var s = myval ?? "new value";

becomes one of the following (depending on preference):

myval -eq $null) { "new value" } else { $myval }
myval -ne $null) { $myval } else { "new value" }

or depending on what $myval might contain you could use:

myval) { $myval } else { "new value" }

and the second C# expression maps in a similar way:

var x = myval == null ? "" : otherval;

becomes

myval -eq $null) { "" } else { $otherval }

Now to be fair, these aren't very snappy, and nowhere near as comfortable to use as the C# forms.

You might also consider wrapping it in a very simple function to make things more readable:

function Coalesce(b) { if (null) { $a } else { $b } }

$s = Coalesce $myval "new value"

or possibly as, IfNull:

function IfNull(b, $c) { if ($a -eq $null) { $b } else { $c } }

$s = IfNull $myval "new value" $myval
$x = IfNull $myval "" $otherval

As you can see a very simple function can give you quite a bit of freedom of syntax.

UPDATE: One extra option to consider in the mix is a more generic IsTrue function:

function IfTrue(b, $c) { if ($a) { $b } else { $c } }

$x = IfTrue ($myval -eq $null) "" $otherval

Then combine that is Powershell's ability to declare aliases that look a bit like operators, you end up with:

New-Alias "??" Coalesce

myval "new value"

New-Alias "?:" IfTrue

q -eq "meaning of life") 42 $otherval

Clearly this isn't going to be to everyone's taste, but may be what you're looking for.

As Thomas notes, one other subtle difference between the C# version and the above is that C# performs short-circuiting of the arguments, but the Powershell versions involving functions/aliases will always evaluate all arguments. If this is a problem, use the if expression form.

2 of 16
108

PowerShell 7 and later

PowerShell 7 introduces many new features and migrates from .NET Framework to .NET Core. As of mid-2020, it hasn't completely replaced legacy versions of PowerShell due to the reliance on .NET Core, but Microsoft has indicated that they intend for the Core family to eventually replace the legacy Framework family. By the time you read this, a compatible version of PowerShell may come pre-installed on your system; if not, see https://github.com/powershell/powershell.

Per the documentation, the following operators are supported out-of-the-box in PowerShell 7.0:

  1. Null-coalescing: ??
  2. Null-coalescing assignment: ??=
  3. Ternary: ... ? ... : ...

These work as you would expect for null coalescing:

a ?? c ?? 'default value'
$y ??= 'default value'

Since a ternary operator has been introduced, the following is now possible, though it's unnecessary given the addition of a null coalescing operator:

a -eq $null ? a

As of 7.0, the following are also available if the PSNullConditionalOperators optional feature is enabled, as explained in the docs (1, 2):

  1. Null-conditional member access for members: ?.
  2. Null-conditional member access for arrays et al: ?[]

These have a few caveats:

  1. Since these are experimental, they're subject to change. They may no longer be considered experimental by the time you read this, and the list of caveats may have changed.
  2. Variables must be enclosed in ${} if followed by one of the experimental operators because question marks are permitted in variable names. It's unclear if this will be the case if/when the features graduate from experimental status (see issue #11379). For example, ${x}?.Test() uses the new operator, but $x?.Test() runs Test() on a variable named $x?.
  3. There is no ?( operator as you might expect if you're coming from TypeScript. The following won't work: $x.Test?()

PowerShell 6 and earlier

PowerShell versions prior to 7 do have an actual null coalescing operator, or at least an operator that is capable of such behavior. That operator is -ne:

# Format:
# (b, null)[0]
($null, 'alpha', 1 -ne $null)[0]

# Output:
alpha

It's a bit more versatile than a null coalescing operator, since it makes an array of all non-null items:

$items = $null, 'alpha', 5, 0, '', @(), $null, $true, $false
$instances = $items -ne $null
[string]::Join(', ', ($instances | ForEach-Object -Process { $_.GetType() }))

# Result:
System.String, System.Int32, System.Int32, System.String, System.Object[],
System.Boolean, System.Boolean

-eq works similarly, which is useful for counting null entries:

($null, 'a', $null -eq $null).Length

# Result:
2

But anyway, here's a typical case to mirror C#'s ?? operator:

'Filename: {0}' -f ($filename, 'Unknown' -ne $null)[0] | Write-Output

Explanation

This explanation is based on an edit suggestion from an anonymous user. Thanks, whoever you are!

Based on the order of operations, this works in following order:

  1. The , operator creates an array of values to be tested.
  2. The -ne operator filters out any items from the array that match the specified value--in this case, null. The result is an array of non-null values in the same order as the array created in Step 1.
  3. [0] is used to select the first element of the filtered array.

Simplifying that:

  1. Create an array of possible values, in preferred order
  2. Exclude all null values from the array
  3. Take the first item from the resulting array

Caveats

Unlike C#'s null coalescing operator, every possible expression will be evaluated, since the first step is to create an array.

🌐
Medium
medium.com › fearthecowboy › powershell-hacks-ternarys-and-null-coalescing-operators-557d1a2fcf5
PowerShell Hacks: Ternarys and Null-coalescing operators | by Garrett Serack🤠 | FearTheCowboy | Medium
March 1, 2017 - // An ugly, bloated mess var answer = SomeFunction(); if( answer == null ) { answer = "not found"; } // Using the null-coalescing operator: var answer = SomeFunction() ?? "not found"; Which offers a clean, tight and simple way of saying if the answer is null, then use this answer instead. Maybe we can do the same thing in PowerShell?
🌐
Toastit
toastit.dev › 2020 › 03 › 10 › ps7now-null-conditional
Exploring... Nothing? PowerShell 7's Null Conditional Operators - #PS7Now - ToastIT
March 10, 2020 - A very near relative to the ?? coalescing operator is the ??= conditional assignment operator. With this operator, the variable on the left will keep its current value if it is not null, but will be assigned the value on the right if it is null.
🌐
Itluke
itluke.online › 2020 › 03 › 22 › use-cases-for-the-new-null-coalescing-operator-in-powershell-7
Use cases for the new null coalescing operator in PowerShell 7
March 21, 2020 - It would be tempting to use the -Not operator on the left side of the coalescing operator. For example, instead of creating a folder that does not exist, you want to remove an existing folder. However, the opposite of $null is $true, but there is no way in PowerShell of making the opposite of something equal to $null and, as a consequence, the right side of the coalescing operator would never be executed.
🌐
Willpage
willpage.dev › 2023 › 02 › 21 › null-or-empty-string-coalesce-in-powershell-7
Null or Empty String Coalesce in PowerShell 7
February 20, 2023 - The -not operator reverses this so it returns True if it’s null or empty and False if it has a non-zero length value. Therefore we’re saying if the $inputString variable is null or empty, then output $null otherwise output the value of the string variable. Next we use the null coalescing operator to simply coalesce the null with the replacement text.
🌐
Microsoft Learn
learn.microsoft.com › en-us › powershell › module › microsoft.powershell.core › about › about_operators
about_Operators - PowerShell | Microsoft Learn
For more information, see about_If. The null-coalescing operator ?? returns the value of its left-hand operand if it isn't null. Otherwise, it evaluates the right-hand operand and returns its result.
🌐
ByteInTheSky
byteinthesky.com › home › powershell › null coalescing operator in powershell
Null Coalescing Operator in PowerShell - ByteInTheSky
December 28, 2022 - Null coalescing is a powerful feature in PowerShell that helps simplify scripts by providing a way to assign default values to variables when left-hand operand is null.
Find elsewhere
🌐
GitHub
github.com › PowerShell › PowerShell › issues › 17282
Null-coalescing assignment operator ??= Fails When Assigning to Strongly-Typed Variables · Issue #17282 · PowerShell/PowerShell
May 6, 2022 - Refer to Differences between Windows PowerShell 5.1 and PowerShell. The null-coalescing assignment operator ??= is supposed to "assign the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null."
Published   May 06, 2022
🌐
Wikipedia
en.wikipedia.org › wiki › Null_coalescing_operator
Null coalescing operator - Wikipedia
October 31, 2025 - The null coalescing operator is a binary operator that is part of the syntax for a basic conditional expression in several programming languages, such as (in alphabetical order): C# since version 2.0, Dart since version 1.12.0, PHP since version 7.0.0, Perl since version 5.10 as logical defined-or, PowerShell since 7.0.0, and Swift as nil-coalescing operator.
🌐
Mohitgoyal
mohitgoyal.co › 2021 › 02 › 03 › using-null-coalescing-operator-in-powershell-7
Using Null Coalescing Operator in PowerShell 7 – mohitgoyal.co
January 21, 2021 - PowerShell 7 introduces null coalescing operator (??) to make it easy to identify the variable or expression on the left side is null or not.
🌐
Wordpress
richardspowershellblog.wordpress.com › 2019 › 10 › 28 › null-coalescing-with-object-properties
Null coalescing with Object properties | Richard Siddaway's Blog
October 28, 2019 - 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. ... 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.
🌐
GitHub
github.com › PowerShell › PowerShell › issues › 3240
Suggestion: implement null-coalescing, null-conditional access (null-soaking), null-conditional assignment · Issue #3240 · PowerShell/PowerShell
March 2, 2017 - $fallbackValue # null-coalescing # $varThatMayBeNull?.Name # null-conditional access, for Set-StrictMode -Version 2+ $varThatMayBeNull?[42] # ditto, with indexing · Re null-conditional access: With Set-StrictMode being OFF (the default), you can just use $varThatMayBeNull.Name - no special syntax needed; however, if Set-StrictMode -Version 2 or higher is in effect, $varThatMayBeNull.Name would break and that's where the null-conditional operator (?.) is helpful, to signal the explicit intent to ignore the $null in a concise manner.
Published   Mar 02, 2017
🌐
GitHub
github.com › PowerShell › PowerShell › pull › 10636
Implement Null Coalescing and Null Coalescing assignment operators by adityapatwardhan · Pull Request #10636 · PowerShell/PowerShell
adityapatwardhan:NullAssignmentadityapatwardhan/PowerShell:NullAssignmentCopy head branch name to clipboard ... Implement the Null Coalescing ?? and Null Coalescing Assignment ??= operators.
Author   PowerShell
🌐
LazyAdmin
lazyadmin.nl › home › powershell operators [complete guide]
PowerShell Operators [Complete Guide] — LazyAdmin
August 22, 2024 - One of the nice things about the Null-coalescing Operators is that it allows you to, for example, only access a property of an object if that object is not null: # Define an object with a property $person = [PSCustomObject]@{ Name = "Alice" } # Access the 'Name' property only if $person is not null $name = $person?.Name · There are a lot of operators in PowerShell ...
🌐
Microsoft
devblogs.microsoft.com › dev blogs › powershell team › powershell 7 preview 5
PowerShell 7 Preview 5 - PowerShell Team
November 19, 2019 - This works with both native commands as well as PowerShell cmdlets or functions. Prior to this feature, you could already do this by use of if statements along with checking if $? indicated that the last statement succeeded or failed. This new operator makes this simpler and consistent with other shells. Often in your scripts, you may need to check if a variable is $null or if a property is $null before using it. The new Null conditional operators makes this simpler. The new ?? null coalescing operator removes the need for if and else statements if you want to get the value of a statement if it’s not $null or return something else if it is $null.
🌐
Dutchscriptingguys
dutchscriptingguys.com › coalescing-in-powershell-7
Coalescing in PowerShell 7 – Tulips, Windmills & PowerShell: Dutch Scripting Guys
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 ??
🌐
Microsoft Learn
learn.microsoft.com › en-us › powershell › module › microsoft.powershell.core › about › about_assignment_operators
about_Assignment_Operators - PowerShell | Microsoft Learn
In the following example, the $d ... null-coalescing assignment operator ??= assigns the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null....
🌐
TutorialsPoint
tutorialspoint.com › which-are-the-new-null-operators-introduced-in-powershell-version-7
Which are the new Null Operators introduced in PowerShell version 7?
PowerShell version 7 has introduced a few new null operators. They are as below. Null-Coalescing operator - ?? Null Conditional Assignment Operators - ??= Null Conditional member access oper