Home » How to Get String Length in PowerShell

How to Get String Length in PowerShell

You can get the length of a string in PowerShell using the Length property of the Measure-Object cmdlet.

The following methods show how you can do it.

Method 1: Using the Length property

$string = "ActiveDirectoryTools"
$string.Length

This example will return the string length.

Method 2: Using the Measure-Object cmdlet

$string = "ActiveDirectoryTools"
($string | Measure-Object -Character).Characters

This example will output the length of the string.

The following examples show how you can use these methods.

Get String Lenth Using Length Property in PowerShell

The Length property is an easy way to get the string length.

# define the string
$string = "ActiveDirectoryTools"

# Get the length of string
$stringLength = $string.Length

Write-Output "The length of the string is: $stringLength"

Output:

PowerShell get string length using Length property
PowerShell get string length using Length property

In this script, the $string variable contains the string data “ActiveDirectoryTools“. The Length property is used to get the length of a string and store it in the $stringLength variable.

Finally, the Write-Output cmdlet outputs the length of a string to the console.

Get the String Length Using the Measure-Object Cmdlet

You can use the Measure-Object cmdlet in PowerShell to get the string length.

# define the string
$string = "ActiveDirectoryTools"

# Get the length of string
$stringLength = ($string | Measure-Object -Character).Characters

Write-Output "The length of the string is: $stringLength"

Output:

PowerShell get string length using Measure-Object
PowerShell get string length using Measure-Object

In this script, the $string variable contains the “ActiveDirectoryTools“. We then use the Measure-Object cmdlet to count the characters in the string. It returns the string length and stores it in the $stringLength variable.

Finally, we use the Write-Output cmdlet to output the length of the string.

Conclusion

I hope the above article on getting the string length in PowerShell is helpful to you.

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