PowerShell

PowerShell: $null vs ::IsNullOrEmpty

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?

Anmerkung 2020-04-13 125542.png

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.

Anmerkung 2020-04-13 125053.png

Which brings me to $justempty. What will happen here?

Anmerkung 2020-04-13 125314.png

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.

Anmerkung 2020-04-13 130054.png

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

Tagged as: ,

6 replies »

  1. 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?

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.