The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,676 other followers

PowerShell: Do not take a shortcut while testing NULL values.

Posted by jpluimers on 2014/03/05

A while ago I found a blog post explaining how to shortcut testing NULL values with PowerShell.

Do not do that!

I agree with the quote on the blog:

One thing you may not forget is that Powershell is a lot more friendly for NULL values than C#, so don’t forget to check your objects for NULL values. In Powershell this is very clean and easy to do.

But it is also easy to get wrong:

To see if a variable is null, simply check:

If (!$Variable) {some action}

Conversely, to verify if the variable has any value:

If ($Variable) {some action}

Just a few examples. Now quess the outcome for all of them.

$a=$null;  if ($a) {"'$a' has VALUE"} else {"'$a' is NULL"}
$a=$false; if ($a) {"'$a' has VALUE"} else {"'$a' is NULL"}
$a=0;      if ($a) {"'$a' has VALUE"} else {"'$a' is NULL"}
$a='';     if ($a) {"'$a' has VALUE"} else {"'$a' is NULL"}
$a="";     if ($a) {"'$a' has VALUE"} else {"'$a' is NULL"}
$a=1;      if ($a) {"'$a' has VALUE"} else {"'$a' is NULL"}

Now take an educated guess on the outcome.

Did you expect everything but 1 to be NULL? Right: they aren’t, but the outcome is:

'' is NULL
'False' is NULL
'0' is NULL
'' is NULL
'' is NULL
'1' has VALUE

So better stick to the long version

$a=$null;  if ($a -ne $null) {"'$a' has VALUE"} else {"'$a' is NULL"}
$a=$false; if ($a -ne $null) {"'$a' has VALUE"} else {"'$a' is NULL"}
$a=0;      if ($a -ne $null) {"'$a' has VALUE"} else {"'$a' is NULL"}
$a='';     if ($a -ne $null) {"'$a' has VALUE"} else {"'$a' is NULL"}
$a="";     if ($a -ne $null) {"'$a' has VALUE"} else {"'$a' is NULL"}
$a=1;      if ($a -ne $null) {"'$a' has VALUE"} else {"'$a' is NULL"}

gets you much better results: only $null is in fact NULL:

'' is NULL
'False' has VALUE
'0' has VALUE
'' has VALUE
'' has VALUE
'1' has VALUE

–jeroen

via: The art of simplicity: Testing NULL values with Powershell.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

 
%d bloggers like this: