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( <<<< )