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

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

In PowerShell, you can use the [string]::IsNullOrEmpty() method or the [string]::IsNullOrWhiteSpace() method to check if a string is empty or null.

The following methods show how to do it with examples.

Using [string]::IsNullOrEmpty()

You can use [string]::IsNullOrEmpty() method to check if a string is empty or null in PowerShell. Here’s how you can do it in PowerShell.

# define a string
$string = ""

if([string]::IsNullOrEmpty($string)){
  
          Write-Output "The string is empty, null or contains only whitespace."
}
else {
         Write-Output "The string is not empty or null."
}

Output:

PowerShell check if string is empty or null
PowerShell check if string is empty or null

In this example, we define a string variable $string that contains the string type data. You can set it to $null or ” ” to test.

We then use the [string]::IsNullOrEmpty() method to check if a string $string is empty or null. The [string]::IsNullOrEmpty() method returns $true if the string is either $null or has zero length.

In the if statement, we check for condition check and output the result on the terminal.

After running the PowerShell script, the above program will output “The string is empty, null or contains only whitespace.” as the $string variable is empty.

Using [string]::IsNullOrWhiteSpace() Method

Another way to check if a string is null or contains the whitespace is by using the [string]::IsNullOrWhiteSpace() method.

Here’s how you can do it.

# define a string
$string = ""

if([string]::IsNullOrWhiteSpace($string)){
  
          Write-Output "The string is empty, null or contains only whitespace."
}
else {
         Write-Output "The string is not empty or only whitespace."
}

Output:

PowerShell check if string is empty or contains whitespace
PowerShell check if string is empty or contains whitespace

In this example, we define a string variable $string that contains the string type data. You can set it to $null or ” ” to test.

We then use the [string]::IsNullOrWhiteSpace() method to check if a string $string is empty or contains whitespace.

The [string]::IsNullOrWhiteSpace() method returns $true if the string is either $null or has zero length or contains only whitespace characters like spaces, tabs, and line breaks.

In the if statement, we check for condition check and output the result on the terminal.

After running the PowerShell script, the above program will output “The string is empty, null or contains only whitespace.” as the $string variable is empty.

Conclusion

I hope the above article on checking if a string is empty or null in PowerShell is helpful to you.

You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.