PowerShell and Null Values
I love Windows PowerShell, I really do. However, some of its language features drive me crazy sometimes. One of those is propagation of null values on expressions involving the ‘.’ operator for property access.
Basically the problem is this: Suppose you have a variable $x, and you reference a property on it. In languages like C#, if the $x holds a null value, you’d expect an error. In PowerShell, instead, the null value of $x propagates through as many chained property access expressions are there so that the end return of said expression is also a null value.
Let me explain with an example:
$xp = $null
$val = $xp.Site.Lists.Count
$val -eq $null
>> True As you can see, referencing $xp.Site.Lists.Count above results in, well, nothing: You get a null value.
Given the nature of PowerShell and much of its intended audience, this behavior sort of make sense. My problem with it is that it can lead to subtle problems that will some times annoy me to no end; for example if you’ve got a complex expression involving several chained property accesses, it’s hard to know which of those returned the original null value that got propagated. It’s annoying to debug, at least.
It can also lead to more subtle behaviors. For example, if your expression was meant to return an enumerable object (such as an array or collection) and you were using that as input to a pipeline, you’ll get an unexpected behavior: The pipeline will execute with a single $null input value:
$xp.Site.Lists | %{
"Holy Moses, `$_ is `$null? $($_ -eq $null)"
}
>> Holy Moses, $_ is $null? True This was a bit unexpected to me the first time it happened, though it sort of makes sense in sick sort of way :-).
An interesting asymmetry, however, is that the null value propagation stops if there’s a method call in there:
$xp.Site.Lists.Call()
>> You cannot call a method on a null-valued expression.
>> At line:1 char:20
>> + $xp.Site.Lists.Call( <<<< )






As an interactive shell, having PowerShell not error out on missing properties was pretty important. However, when scripting, missing propertues can be a real source of bugs. This is why we added ‘Set-PSDebug -strict’ (V1, V2) or ‘Set-StrictMode -version 2′ (v2 only) to allow you to catch these errors. Since there were no useful scenarios for method calls on null even in interactive cases, we never allowed it.
Thanks,
-bruce
Thanks for the comment, Bruce. I agree with the general theme, but I’m not sure I completely agree that propagating the null value that way is always useful. It’s hard to balance making the tool easier less in-your-face about errors, but also avoid pitfalls like this one.
I’ll be sure to check out set-strictmode in v2!