You guys are making this too hard. PowerShell handles this quite elegantly e.g.:

> $str1 = $null
> if ($str1) { 'not empty' } else { 'empty' }
empty

> $str2 = ''
> if ($str2) { 'not empty' } else { 'empty' }
empty

> $str3 = ' '
> if ($str3) { 'not empty' } else { 'empty' }
not empty

> $str4 = 'asdf'
> if ($str4) { 'not empty' } else { 'empty' }
not empty

> if ($str1 -and $str2) { 'neither empty' } else { 'one or both empty' }
one or both empty

> if ($str3 -and $str4) { 'neither empty' } else { 'one or both empty' }
neither empty
Answer from Keith Hill on Stack Overflow
🌐
Microsoft Learn
learn.microsoft.com › en-us › powershell › scripting › learn › deep-dives › everything-about-null
Everything you wanted to know about $null - PowerShell | Microsoft Learn
June 11, 2024 - You may have noticed that I always place the $null on the left when checking for $null in my examples. This is intentional and accepted as a PowerShell best practice. There are some scenarios where placing it on the right doesn't give you the expected result. Look at this next example and try to predict the results: if ( $value -eq $null ) { 'The array is $null' } if ( $value -ne $null ) { 'The array is not $null' }
Discussions

how to check a value is that null in powershell script
I want to check the PasswordLastSet value of the user is that empty. PS Z:\> Get-ADUser -Identity test1 -Properties * | select passwordlastset passwordlastset --------------- By if to judgment is that null. this is my script $password =… More on learn.microsoft.com
🌐 learn.microsoft.com
1
0
September 10, 2020
powershell - Check if a string is not NULL or EMPTY - Stack Overflow
You can use the [string]::IsNullOrEmpty($version) method if it is a string. But, I was looking for a universal way to check nulls (regardless of data type) in Powershell. Checking for null (or not null) values in PowerShell is tricky. Using ($value -eq $null) or ($value -ne $null) does not ... More on stackoverflow.com
🌐 stackoverflow.com
PowerShell $null Variable in an IF Statement
I know I’m going to be kicking myself, but since I still consider myself a n00b with PS, I’ll try not to kick too hard. I’ve got a script for new hires that works intermittently. HR insists that AD accounts use a person’s legal name, however many people prefer their nicknames for their ... More on community.spiceworks.com
🌐 community.spiceworks.com
8
5
March 10, 2016
Null coalescing in PowerShell - Stack Overflow
By the time you read this, a compatible ... 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: ... Ternary: ... ? ... : ... These work as you would expect for null coale... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Thomas Maurer
thomasmaurer.ch › home › powershell: check variable for null
Powershell: check variable for null - Thomas Maurer
December 21, 2020 - If you are working a lot with PowerShell parameters and inputs you need to check if variables have the right value and are not 'null'. Here is how you can check a PowerShell variable is null. In addition, I am also going to share how you can use the Null conditional operators in PowerShell 7. PowerShell check variable for null The normal if -eq '$null' doesn't work: if ($varibalename -eq $null) { Write-Host 'variable is null' } Now how you can check that (check if $variablename has $null as value): if (!$variablename) { Write-Host 'variable is null' } And here if
🌐
LazyAdmin
lazyadmin.nl › home › powershell – check if variable is null or empty
PowerShell - Check if variable is Null or Empty — LazyAdmin
April 9, 2024 - But when you place $null it on the right-hand side, then it will return everything from the array, that does not equal $null. If you are using PowerShell 7, and you actually should, then you can use one of the new null conditional operators to quickly check if a variable or property is null or not.
🌐
SharePoint Diary
sharepointdiary.com › sharepoint diary › powershell › how to check for null, not null, or empty in powershell?
How to Check for Null, Not Null, or Empty in PowerShell? - SharePoint Diary
September 28, 2025 - The following code snippet shows ... not null - example $var = "Hello, world!" if ($var -ne $null) { Write-Host "The variable is not null." } else { Write-Host "The variable is null."...
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 92154 › how-to-check-a-value-is-that-null-in-powershell-sc
how to check a value is that null in powershell script - Microsoft Q&A
September 10, 2020 - $password = Get-ADUser -Identity test1 -Properties * | select passwordlastset if ($password.passwordlastset -eq $null){ Write-Output "It's empty" } else { Write-Output "It isn't empty" }
Find elsewhere
Top answer
1 of 8
1

The problem is here:

$UserPref = if ($UserPref -eq $null){$UserPrefN = $UserGN} Else{$UserPrefN = $UserPref}

You’re doing a comparison on the $UserPref variable which has not been set because the comparison is in the assignment statement. This is not technically illegal, but you have strict mode on which will throw an error when you reference a variable that hasn’t been initiated. You can avoid this error by skipping the Set-StrictMode cmdlet.

However, the way you are assigning the $UserPref variable seems a bit wonky to me. It looks like you’re trying to check if it’s already set and then set some other variable values based on this comparison. Since each action you’re taking in the if construct is an assignment, there is no need to encapsulate those in the $UserPref assignment. Also, instead of checking for -eq $null in the if condition, you could just check for the existence of $UserPref:

if (!$UserPref){$UserPref = $UserGN}
2 of 8
5

I know I’m going to be kicking myself, but since I still consider myself a n00b with PS, I’ll try not to kick too hard.

I’ve got a script for new hires that works intermittently. HR insists that AD accounts use a person’s legal name, however many people prefer their nicknames for their email and display names, so a PreferredName field was created in HRIS. I’m checking for a preferred name ($UserPref) and if it exists I assign it to $UserPrefN and if it doesn’t, I assign their first name ($UserGN) to $UserPrefN. If $UserPref is blank ($null), sometimes it works and sometimes it doesn’t, lately more often than not it doesn’t and $UserPrefN doesn’t get set. It’s got to be my syntax, but I don’t see it.

[PS] C:\Windows\system32>Set-Strictmode -Version Latest -Verbose
[PS] C:\Windows\system32>$User = 'AccountName'
[PS] C:\Windows\system32>$UserSN = 'LastName'
[PS] C:\Windows\system32>$UserGN = 'FirstName'
[PS] C:\Windows\system32>$UserFI = $UserGN.substring(0,1)
[PS] C:\Windows\system32>$UserPref =
>> if ($UserPref -eq $null){$UserPrefN = $UserGN} Else{$UserPrefN = $UserPref}
>>
The variable '$UserPref' cannot be retrieved because it has not been set.
At line:2 char:5
+ if ($UserPref -eq $null){$UserPrefN = $UserGN} Else{$UserPrefN = $UserPref}
+     ~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (UserPref:String) [], RuntimeException
    + FullyQualifiedErrorId : VariableIsUndefined

[PS] C:\Windows\system32>
[PS] C:\Windows\system32>echo $UserPrefN
The variable '$UserPrefN' cannot be retrieved because it has not been set.
At line:1 char:6
+ echo $UserPrefN
+      ~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (UserPrefN:String) [], RuntimeException
    + FullyQualifiedErrorId : VariableIsUndefined

Top answer
1 of 16
248

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

There isn’t any 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.

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 documentation (1 and 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 nonnull 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.

🌐
PowerShell Forums
forums.powershell.org › powershell help
Checking for NULL in PS - PowerShell Help - PowerShell Forums
July 4, 2018 - Hello Scripting Experts, I have extracted a simple file via the Import-Excel command as follows: > Import-Excel $infile -Noheader -Dataonly -Startrow 2 | Select P2,P3,P4,P5 | Foreach-Object { If ($_.P2 = NULL ???) … My objective is to check the property P2 for a NULL (i.e., empty) value (not quite the same as blanks).
🌐
Thinkpowershell
thinkpowershell.com › test-powershell-variable-for-null-empty-string-and-white-space
Test PowerShell Variable for Null, Empty String, and White Space
October 25, 2017 - PS C:\> $Service = Get-CimInstance -ClassName Win32_Service -Filter "Name='AMD External Events Utility'" $Service.Description -eq "" -or $Service.Description -eq $null True · This works, but you have to always remember to code for two comparisons, and it is twice as much work as a single comparison. Luckily, there is a .NET String method we can take advantage of directly called IsNullOrEmpty. To use this within PowerShell, we type [string]::IsNullOrEmpty($variable) to use the .NET class’ method:
🌐
Powershellexplained
powershellexplained.com › 2018-12-23-Powershell-null-everything-you-wanted-to-know
Everything you wanted to know about $null - Powershell
December 23, 2018 - PS> function Get-Nothing {} PS> $value = Get-Nothing PS> $null -eq $value True · $null values will impact your code differently depending on where they show up. If you use $null in a string, then it will be a blank value (or empty string).
🌐
SPGuides
spguides.com › check-if-a-variable-is-null-or-empty-in-powershell
How to Check if a Variable is Null or Empty in PowerShell?
May 7, 2025 - The best way to check if a variable is null is to compare it directly with the $null special value in PowerShell.
🌐
EDUCBA
educba.com › home › data science › data science tutorials › powershell tutorial › powershell null
PowerShell null | How does $null Variable Works in PowerShell | Examples
March 6, 2023 - PowerShell treats $Null object with the value null and some commands require some output to generate and they generate value null if there is any error and can also be useful in the troubleshooting purpose in the scripts to check if the command ...
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
SID-500.COM
sid-500.com › 2021 › 07 › 07 › powershell-null-vs-isnullorempty
PowerShell: $null vs ::IsNullOrEmpty – SID-500.COM
July 7, 2021 - Now we explore the ::IsNullOrEmpty statement. It’s a .NET statement to figure out, if a value is null or empty. Not surprisingly, both value show true, because the first one is empty and the second one is just nothing, so it is $null.
🌐
ShellGeek
shellgeek.com › home › powershell › powershell $null – check for null
PowerShell $null - Check for null - ShellGeek
April 14, 2024 - To avoid error while accessing index in collection, check if it contains $null. PS C:\> $languages = @('C#','PowerShell','Java') PS C:\> $null -eq $languages[4] TRUE
🌐
Cody Konior
codykonior.com › 2013 › 10 › 17 › checking-for-null-in-powershell
Checking for null in PowerShell
October 17, 2013 - [string] $a = $null $a -eq $null # False $a -eq "" -and $a -eq [String]::Empty # True if (!$a) { Write-Host "True" } else { Write-Host "False" } # True · That is insidious because if you write a function that explicitly types its argument as [string] PowerShell will prevent you from passing in $null, always converting it to [String]::Empty.
🌐
Rencore GmbH
rencore.com › en › blog › powershell-null-comparison
PowerShell – Null comparison demystified
September 15, 2023 - Because of the type inference methods used in PowerShell the array with the single $null or empty field are being converted to false when the comparison is on the left, and converted to true when there are two $nulls in the array.