PowerShell check if Variable is null – Do $myVar has a value?

Sometimes when writing a script it can be useful to check if a variable is null or does contain a value so to make decision. How do I check if a variable is null?

The standard if -eq $null approach does not working when dealing with variables so this is not something that will work

if ($myVar -eq $null) { Write-Host 'Variable does not contain any value*' }

If you want to check if variable is null you can use this sample code

if (!$myVar) { Write-Host 'Variable is null' }

If you want to check if a variable contains any value but $null this is still possible with the following code

if ($myVar) { Write-Host "Variable has the following value: $myVar" }

Leave a comment