PowerShell Script to Extract Substring Easily
$string.Substring(startIndex, length) in PowerShell to extract a substring from a string, where startIndex is the starting position and length is how many characters to take.Examples
How to Think About It
Substring method does exactly this by slicing the string from the start position for the given length.Algorithm
Code
$string = "PowerShell" $startIndex = 5 $length = 4 $substring = $string.Substring($startIndex, $length) Write-Output $substring
Dry Run
Let's trace extracting substring 'Shell' from 'PowerShell' starting at index 5 with length 4.
Set variables
$string = 'PowerShell', $startIndex = 5, $length = 4
Extract substring
$string.Substring(5, 4) returns 'Shell'
Output result
Print 'Shell'
| Operation | Value |
|---|---|
| Input string | PowerShell |
| Start index | 5 |
| Length | 4 |
| Extracted substring | Shell |
Why This Works
Step 1: Using Substring method
The Substring method extracts part of a string starting at startIndex for length characters.
Step 2: Start index is zero-based
Counting starts at zero, so index 5 means the 6th character in the string.
Step 3: Handles length exceeding string end
If length is longer than remaining characters, it returns up to the string's end without error.
Alternative Approaches
$string = "PowerShell" $substring = $string[5..8] -join '' Write-Output $substring
$string = "PowerShell" $substring = ($string -replace '^.{5}(.{4}).*$', '$1') Write-Output $substring
Complexity: O(k) time, O(k) space
Time Complexity
Extracting a substring takes time proportional to the length of the substring k, as it copies those characters.
Space Complexity
The substring requires extra space proportional to its length k, as it creates a new string.
Which Approach is Fastest?
Using Substring is the fastest and most readable. Alternatives like slicing or regex are slower and more complex.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Substring method | O(k) | O(k) | Simple and direct substring extraction |
| Array slicing | O(k) | O(k) | When working with characters as arrays |
| Regex replace | O(n) | O(k) | Complex patterns or conditional extraction |
startIndex is zero-based, causing off-by-one errors.