How to Check if String is Empty in PowerShell (With Examples)


You can use the following basic syntax in PowerShell to check if a string is empty:

if ($my_string) {
echo "String is not empty"
} else {
echo "String is empty"
}

This particular example checks if the string variable named my_string is empty.

If the string is not empty, then String is not empty will be returned.

If the string is empty, then String is empty will be returned.

The following examples shows how to use this syntax in practice.

Example 1: Check if String Equal to $null is Empty

If a string has a value equal to $null then PowerShell will tell us that the string is empty:

PowerShell check if string is null or empty

A value of $null is considered to be empty.

Example 2: Check if String Equal to ” is Empty

If a string has a value equal to then PowerShell will tell us that the string is empty:

A string with beginning and ending quotes and nothing in between is considered to be empty because it contains no characters or whitespace.

Example 3: Check if String Equal to ‘ ‘ is Empty

If a string has a value equal to ‘ ‘ then PowerShell will tell us that the string is not empty:

A value of ‘ ‘ is considered to not be empty because it contains whitespace.

Example 4: Check if String with Characters is Empty

If a string has a value with any number of characters, such as ‘my cool string’, then PowerShell will tell us that the string is not empty:

Any string with one or more characters is considered to not be empty.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Replace Multiple Strings in File
PowerShell: How to Replace Special Characters in String
PowerShell: How to Replace Text in String

Leave a Reply