0
0
PowershellHow-ToBeginner · 2 min read

PowerShell Script to Find Length of String

In PowerShell, you can find the length of a string using the .Length property like this: $string.Length.
📋

Examples

Inputhello
Output5
InputPowerShell
Output10
Input
Output0
🧠

How to Think About It

To find the length of a string, think of counting how many characters it has. In PowerShell, strings have a built-in property called Length that directly gives this count, so you just access that property.
📐

Algorithm

1
Get the input string.
2
Access the string's Length property to get the number of characters.
3
Return or display the length.
💻

Code

powershell
$string = "Hello, World!"
$length = $string.Length
Write-Output "Length of string: $length"
Output
Length of string: 13
🔍

Dry Run

Let's trace the string "Hello, World!" through the code

1

Assign string

$string = "Hello, World!"

2

Get length

$length = $string.Length # 13 characters

3

Output length

Write-Output "Length of string: $length"

VariableValue
$stringHello, World!
$length13
💡

Why This Works

Step 1: String property

Every string in PowerShell has a Length property that stores the number of characters.

Step 2: Accessing length

Using $string.Length reads this property to get the count instantly.

Step 3: Output result

The length value can then be printed or used in further calculations.

🔄

Alternative Approaches

Using Measure-Object
powershell
$string = "Hello"
$length = ($string.ToCharArray() | Measure-Object).Count
Write-Output "Length: $length"
This method converts the string to an array of characters and counts them; it is less direct but useful for learning pipelines.
Using .ToCharArray() and Count property
powershell
$string = "Hello"
$length = $string.ToCharArray().Count
Write-Output "Length: $length"
This also counts characters by converting to an array, but is more verbose than using .Length.

Complexity: O(1) time, O(1) space

Time Complexity

Accessing the Length property is a direct operation and does not depend on string size, so it is O(1).

Space Complexity

No extra memory is needed beyond the input string and a variable to store the length, so O(1).

Which Approach is Fastest?

Using .Length is fastest and simplest. Alternatives using arrays and Measure-Object add overhead and are slower.

ApproachTimeSpaceBest For
.Length propertyO(1)O(1)Simple and fast length retrieval
Measure-Object on char arrayO(n)O(n)Learning pipelines, less efficient
.ToCharArray() and CountO(n)O(n)When array operations needed
💡
Use .Length property for the simplest and fastest way to get string length in PowerShell.
⚠️
Beginners sometimes try to use functions like strlen which do not exist in PowerShell.