Written by 10:18 pm Microsoft, PowerShell • 31 Comments

Powershell: check variable for null

PowerShell 7 Null conditional operators

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 you wanna check if $variablename has any value except $null:

if ($variablename) { Write-Host "variable is NOT null" }

Null assignment and coalescing operators (?? and ??=) in PowerShell 7

If you are running the new PowerShell 7 version, you have new Null conditional operators to make this simpler.

PowerShell 7 Null conditional operators
PowerShell 7 Null conditional operators

With the new PowerShell ?? null coalescing operator to get the value of a statement if it’s not $null or return something else if it is $null. And with the new ??= null conditional assignment operator, you can easily assign a variable a value, but only if the variable is $null.

Here are some examples:

#Variable which is null

$myVariable

#Check variable for null

$myVariable ?? "Is null? True!"

#Check variable for null, and if it is null set the following value

$myVariable ?? "Set the value if null!"

If you want to learn how you can install and update PowerShell 7, check out my blog post.

Conclusion

I hope this helps you to check if your PowerShell variable is null or has a value assigned. If you have any questions, feel free to leave a comment.

Tags: , , , , , , , , , Last modified: December 21, 2020
Close Search Window
Close