BLOG > ARTICLE

PowerShell – Null comparison demystified

3 min read

Blog Header Image

PowerShellI have been working recently on the guidance for PowerShell rules. Rule research requires a lot of research and digging into how a programming language works internally, in order to find validity in community best practices.

One of these best practices is to always compare to powershell $null on the left instead of the right of a comparison. The second part is to not use the short hand by negating the null value as it might confuse the intent of the script.

This is great, it makes sense in one part we know not to confuse the intent of code for other, but why not the other? Why do we have to put null on the left when performing a comparison.

Check out Hugh’s webinar on demand!

Free Risk Assessment

Play time

We have established with the above code, that PowerShell is quite the flexible language when it comes to comparison. Unfortunately this can seriously confuse intent of code and cause supportability issues in the future. What we haven’t fully established is to why we should put the null on the left of the comparison.

To the point

With a help from the community analyzer PSScriptAnalyzer, I know that the culprit is arrays. But we need to reproduce this, and find out why. So more play time!

In the above code we see some strange behaviour. What is going on here?

It isn’t what you expect. Because of the type inference methods used in PowerShell the array with the single $null or empty field are being converted to false when the comparison is on the left, and converted to true when there are two $nulls in the array. This works all the way, when I continued this testing and had three $null objects in the array, again the array didn’t equal null. (It is the whole (!!true) issue all over again.)

This as I’m sure you are aware can cause confused intent in code, and some very unwanted circumstances from happening.

tl;dr

Use $null in comparison on the left hand side. Due to type inference Arrays will be checked for $null with each elements total null count equating.

Over to you!

In order to keep control of your code quality, be it from PowerShell, C#, JavaScript or any language, Rencore’s Risk Assessment will help you discover what’s happening in your SharePoint environment. It detects real production security issues and builds a risk report based on your data. Learn about quick wins for application security and extending SharePoint. Try our Risk Assessment for free today.

Book a Risk Assessement

Hugh Wood

When I don't have my time buried in MSIL and C#, I am passionately writing JavaScript, learning the bleeding edge technologies, building my super awesome computer system, drawing, going to the gym, and spending time with my beautiful girlfriend and cat Momo.