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 comment