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" }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s