Get the Length of a String in PowerShell

There are two methods you can use to count the length of a string in PowerShell:

  • Method 1: Using the Length property of PowerShell String, and
  • Method 2: Using Measure-Object to count the number of characters

We will discuss those two methods working on examples in each case. In the end, we will use the concepts learned to answer these quotes.

  • How to check if a string has more than x characters in PowerShell, and,
  • How to read strings from a file and check their lengths.

Method 1: Using String.Length Property

The <string>.Length is the most straightforward method of getting the length of a string in Powershell. The <string> value can be a literal string or a variable holding the string.

Output:

11

Output:

10

Method 2: Using Measure-Object to Count Character

In this method, a string or a string variable is piped into the Measure-Object command, and characters are counted. Example,

Output:

Lines Words Characters Property
----- ----- ---------- --------
                	17

Output:

Lines Words Characters Property
----- ----- ---------- --------
                	20

Notice that, from the output, we can use Measure-Object to count the number of words and lines in the string by issuing the -Word and -Line options, respectively. You can also supply -IgnoreWhiteSpace to ignore white spaces when counting.

Output:

Lines Words Characters Property
----- ----- ---------- --------
	1 	4     	26

Check if a variable has more than x characters in PowerShell

You can use any of these methods to test if the length of a string or a string variable is greater than a specific value.

Using if-condition

For example,

Output:

True

Other comparison operators you can use include -eq for equals, -ne for not equals, -lt for “less than”, -gt for “greater than”, -le for “less than or equals”, -ge for “greater than or equals.”

Using ternary operator (?) (Available in Windows PowerShell version 7 only)

For example,

Output:
False

Another Example – Reading Strings from a File

In this example, we want to read the contents of a file and then loop through each line checking its length. The file is saved on “C:\Users\kipro\Documents\example.txt” and has the following contents

Lorem Ipsum is simply
dummy text
of the printing and typesetting
industry.
Lorem Ipsum has been
the industry’s standard
dummy text ever
since the 1500s,

The following code should do the job