Practical PowerShell Uncategorized Null. Empty. Space? How to Detect?

Null. Empty. Space? How to Detect?

** Disclaimer ** I do not know everything about PowerShell and I am sure I will miss some methods of detection of empty values. However, what follows is based on my understanding and personal experience.

Let the blog begin.

In scripts that I write, I sometimes need to detect an absence of value. By absence I mean either an empty variable, a variable with a space in it or some other indication that a value expected was not retrieved and thus we need to throw an error OR make a decision based on something missing. Why is this such a hard thing? Based on my experience, the absence is not always detectable with the $Null variable while looking for an empty variable in PowerShell. That being said, let’s review the many methods that can be used to find empty values.

Methods

Here are some sample ways to find a variable that is empty or has no content or value after trying to store something in it.

(1) $Null comparison

$Null – Using the $Null variable to compare against another variable:
[sourcecode language=”powershell”]
If ($Null -eq $MyVariable) { } Else { }
[/sourcecode]
Please note that the $Null variable is on the left side as per best practices. Also not that not every empty variable reads as Null. This using the other methods below may apply better to a particular scenario.

(2) Empty (No Spaces)

We can also check to see if the value is empty using quotes. Make sure not to put a space in-between the quotes for this check.
[sourcecode language=”powershell”]
If ($MyVariable -Eq '') { } Else { }
[/sourcecode]
Now alternatively, sometimes we get a space inserted into the value of the variable.

(3) Spaces Present and Not Null

We can check for it similarly to the above check:
[sourcecode language=”powershell”]
If ($MyVariable -Eq ' ') { } Else { }
[/sourcecode]
This check specifically looks for variables that were populated with a space instead of left as $Null or populated with usable data.

(4) .Net feature – IsNullOrWhiteSpace

Now lastly, we can combine a couple of checks like so:
[sourcecode language=”powershell”]
If (![string]::IsNullOrWhiteSpace($MyVariable)) { } Else { }
[/sourcecode]
The above test is a hybrid of two of the previous checks and IMHO works better than some other checks that I have used. That being said, there is some sort of performance hit from using this. Just be aware that this is not the fastest, but it is the most flexible in terms of what it can matched. …

and that’s it for this article. Hopefully you find this tip to be useful for when you are trying to discover if a value is truly empty, a whitespace or something more valuable.

Further Reading

* $Null
* IsNullOrWhiteSpace
* Code Reference

Related Post