How to Check If a String is Null or Empty in PowerShell

Introduction

When working with string object, it is common to check whether a string is null or empty. In this article, we will show you some methods to check whether a string is null or empty.

Solution

Using IsNullOrEmpty static method

We can use IsNullOrEmpty static method to check whether a string is null or empty.


$str1 = $null
if ([string]::IsNullOrEmpty($str1)) { 'null or empty' } else { 'not null or empty' }

$str2 = ''
if ([string]::IsNullOrEmpty($str2)) { 'null or empty' } else { 'not null or empty' }

$str3 = ' '
if ([string]::IsNullOrEmpty($str3)) { 'null or empty' } else { 'not null or empty' }

Above code will give the below result:


null or empty
null or empty
not null or empty

Cast String to Boolean

To check whether a string is null or empty, we can also cast the string to boolean implicitly or explicitly.

Below is the example of casting the string to boolean implicitly.


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

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

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

Above code will give below output:


null or empty
null or empty
not null or empty

We can also cast the string to boolean explicitly which adds readability to our code.


$str1 = $null
if ([bool]$str1) { 'not null or empty' } else { 'null or empty' }

$str2 = ''
if ([bool]$str2) { 'not null or empty' } else { 'null or empty' }

$str3 = ' '
if ([bool]$str3) { 'not null or empty' } else { 'null or empty' }

Above code will give the same result as previous example:


null or empty
null or empty
not null or empty

Conclusion

In PowerShell, there are two ways to check whether a string is null or empty: using IsNullOrEmpty static method and casting the string to boolean. However, the former method is recommended as it is more obvious.