PowerShell: How to Check if String Contains Any Letters


You can use the following syntax in PowerShell to check if a string contains any letters:

$my_string -match "[a-z]"

This particular example checks if the string stored in the variable named $my_string contains any letters and return True or False as a result.

You could also use an if else statement to output specific text as a result:

if ($my_string -match "[a-z]") {
  Write-Host "String contains letters" 
} else {
  Write-Host "String does not contain letters"
}

Note: The syntax [a-z] is case-insensitive in PowerShell and will return True if any lowercase or uppercase letters are found in the string.

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

Example: How to Check if String Contains Letters in PowerShell

Suppose we have a string variable with the following value in Powershell:

  • 1234

We can use the following syntax to check if this string contains any letters:

$my_string = "1234"
$my_string -match "[a-z]" 

The following screenshot shows how to use this syntax in practice:

This returns False since the variable named $my_string does not contain any letters.

Suppose instead we have a variable with the following value:

  • Zach1234

We can use the following syntax to check if this string contains any letters:

$my_string = "Zach1234"
$my_string -match "[a-z]" 

The following screenshot shows how to use this syntax in practice:

PowerShell check if string contains any letters

This returns True since the variable named $my_string does contain letters.

We could also use an if else statement to return specific output:

$my_string = "Zach1234"

if ($my_string -match "[a-z]") {
  Write-Host "String contains letters" 
} else {
  Write-Host "String does not contain letters"
}

The following screenshot shows how to use this syntax in practice:

PowerShell if else statement to check if variable contains letters

This returns “String contains letters” since the string variable does indeed contain letters.

Related Tutorials

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

PowerShell: How to Replace Text in String
PowerShell: How to Extract Text Between Two Strings
PowerShell: How to Check if String Exists in List of Strings
PowerShell: How to Replace Every Occurrence of String in File

Leave a Reply