GeekBits

PowerShell Check if String Is Empty

We can use various methods to check whether a string is emptu in PowerShell as we will explore in this tutorial. Let us dive in.

2 min read
PowerShell Check if String Is Empty

In PowerShell, a string refers to sequence of characters enclosed in either single (' ') or double (" ") quotation marks. It can contain letters, numbers, symbols, spaces, and any combination of characters.

An empty string in PowerShell is a string that contains no characters. It is essentially a string with a length of zero.

Method 1 - Using the -eq Operator

We can use the -eq (equals) operator to compare a string with an empty string. If they are equal, the string is empty.

$myString = ""
if ($myString -eq "") {
    Write-Host "The string is empty."
} else {
    Write-Host "The string is not empty."
}

Method 2 - Using Length Property

The Length property of a string gives us the number of characters in the string. If the length is 0, the string is empty.

$myString = ""
if ($myString.Length -eq 0) {
    Write-Host "The string is empty."
} else {
    Write-Host "The string is not empty."
}

Method 3 - Using String.IsNullOrEmpty() Method

PowerShell has a built-in method String.IsNullOrEmpty() that we can use to check if a string is empty or null.

$myString = ""
if ([string]::IsNullOrEmpty($myString)) {
    Write-Host "The string is empty or null."
} else {
    Write-Host "The string is not empty."
}

Method 4 - Using Regular Expressions

We can also use regular expressions to check if a string contains only white spaces.

$myString = "   "
if ($myString -match "^\s*$") {
    Write-Host "The string is empty or contains only white spaces."
} else {
    Write-Host "The string is not empty."
}

Method 5 -Using Trim() Method

PowerShell also contains a Trim() method that we can use to remove leading and trailing white spaces from a string. After trimming, if the string is empty, it originally contained only white spaces.

$myString = "   "
$trimmedString = $myString.Trim()
if ($trimmedString.Length -eq 0) {
    Write-Host "The string is empty or contains only white spaces."
} else {
    Write-Host "The string is not empty."
}

Method 6 - Using a Custom Function

We can create a custom function to encapsulate the logic for checking if a string is empty. This can be useful if we need to perform this check frequently in your scripts.

Function Is-StringEmpty($inputString) {
    if ($inputString -eq "") {
        return $true
    } else {
        return $false
    }
}

$myString = ""
if (Is-StringEmpty $myString) {
    Write-Host "The string is empty."
} else {
    Write-Host "The string is not empty."
}

Done.

Conclusion

This demonstrates the methods of checking if a string is empty using various powershell features and functions.

Sign up for our newsletter

Don't miss anything. Get all the latest posts delivered to your inbox. No spam!