How to Get String Length of Variable in PowerShell


You can use the following syntax to return the string length of a variable in PowerShell:

$my_string.Length

This particular example will return the length of the string stored in the variable named $my_string.

If you’d like, you can use the following syntax to check if the length of a string is greater than a certain number:

if ($my_string.Length -gt 10) {
    Write-Output "String Length greater than 10" }
else {
    Write-Output "String Length not greater than 10"
}

This particular example will check if the length of the string stored in the variable named $my_string is greater than 10 and return a specific string based on the result.

The following examples show how to use each method in practice.

Example 1: Get String Length of Variable in PowerShell

We can use the following syntax to define a string variable in PowerShell and then return the string length of the variable:

$my_string = "Hello everyone!"

$my_string.Length

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

PowerShell get string length of variable

We can see that the string stored in the variable named $my_string has a length of 15.

Note that this length includes all alphabetical characters in the string along with the space and the exclamation point.

Example 2: Get String Length of Variable in PowerShell

We can use the following syntax to define a string variable in PowerShell and then check if the length of the string variable is greater than 10:

$my_string = "Hello everyone!"

if ($my_string.Length -gt 10) {
    Write-Output "String Length greater than 10" }
else {
    Write-Output "String Length not greater than 10"
}

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

PowerShell if string length greater than

The if else statement returns String Length greater than 10 since the length of the string (15) is indeed greater than 10.

Note that you could also use the following operators when comparing the string length to a specific number:

  • lt: less than
  • le: less than or equal to
  • gt: greater than
  • ge: greater than or equal to
  • eq: equal
  • ne: not equal

Feel free to use whichever operator you would like.

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