Null is null. Dividing by zero is not allowed, say the mathematicians. What about null in PowerShell? Is null equal empty? What is $null? Why a method IsNullOrEmpty? In this blog post I will shed some on this and provide you with some examples to understand the differences between null and null or empty.
Starting Condition
Let’s consider two variables, one of them is an empty string, the other is just nothing.
$emptystring = '' $justempty
$null
What will happen if we check whether $emptystring is equal $null?
False? What the heck? $emptystring is empty, so it must be null! No, it is indeed empty, but it’s not nothing. It’s just an empty string.
Which brings me to $justempty. What will happen here?
Oh, right, $justempty is really empty, so it is $null. Simply put, it is just nothing.
[]::IsNullOrEmpty
Now we explore the ::IsNullOrEmpty statement. It’s a .NET statement to figure out, if a value is null or empty. Not surprisingly, both value show true, because the first one is empty and the second one is just nothing, so it is $null.
Nice. Mission accomplished.
Keep on working with PowerShell! See you next time.
See also
PowerShell 7: Pipeline Chain Operators && and ||
PowerShell Last Operation Status Variable: $?
Categories: PowerShell
I use this even with Where-Object.
for example:
Get-ItemProperty -Path ‘HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*’ | `
Where-Object { !([string]::IsNullOrEmpty($_.DisplayName)) } | Export-Csv -Path “C:\InstalledSW.csv” -NoTypeInformation
As far as I tested, it works, maybe you have a better solution.
Maybe you want to add this possibility?
LikeLike
Looks good! Thank you
LikeLike
Nice topic selection and good illustration. Examples for differentiating null and isnullorempty is also excellent.
LikeLike