How to check if a string is null or empty in PowerShell?

It’s straightforward to check if the string is null or empty in C# and Java. However, in PowerShell, it is slightly tricky as it does not hold a null value.
There are two best ways to verify if the string is null or empty, and let’s look at both approaches with examples.

How to check if a string is null or empty in PowerShell?

While writing PowerShell scripts, it would be best to remember that any null will be converted into empty strings. So even if you pass any null value to commandlet or functions, it will be converted to an empty string.

Using IsNullOrEmpty() Static Method

PowerShell comes up with a built-in static method named IsNullOrEmpty() which could verify the null or empty check.

Syntax:

[string]::IsNullOrEmpty(...)

Example of IsNullOrEmpty() in PowerShell

$str1 = $null
[string]::IsNullOrEmpty($str1)

The above code returns true which mean the string is empty.

Using conditional Statement

The second approach is to use a conditional statement to verify if the string is empty or null. Let’s take a look at the different examples and scenarios.

> $str1 = $null
> if ($str1) { 'not empty' } else { 'empty' }
empty

> $str2 = ''
> if ($str2) { 'not empty' } else { 'empty' }
empty

> $str3 = ' '
> if ($str3) { 'not empty' } else { 'empty' }
not empty

> $str4 = 'asdf'
> if ($str4) { 'not empty' } else { 'empty' }
not empty

> if ($str1 -and $str2) { 'neither empty' } else { 'one or both empty' }
one or both empty

> if ($str3 -and $str4) { 'neither empty' } else { 'one or both empty' }
neither empty

Using IsNullOrWhiteSpace()

We can also use the method IsNullOrWhiteSpace() from the “System.String” class to detect a given string is NULL or EMPTY and whether it has Whitespace.

Note: The method IsNullOrWhiteSpace() is available only from .NET Frmaework 4.0 and hence it works only on Powershell 3.0+ versions.

$mystring = " "           
IF([string]::IsNullOrWhiteSpace($mystring)) {            
    Write-Host "String is either null or empty or has whitespace"           
} else {            
    Write-Host "Your string is not empty"           
}  
Leave a Reply

Your email address will not be published. Required fields are marked *

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like