When working with strings in PowerShell, I often need to extract characters from the end of a string. Whether it’s parsing log files, manipulating file names, or processing data from APIs, getting a substring from the end is a common requirement.
In this article, I’ll show you several methods to extract a substring from the end of a string in PowerShell. I’ll cover both basic and advanced techniques that I’ve used throughout my PowerShell career.
What is a Substring and Why Extract From the End?
A substring is simply a portion of a string. While PowerShell’s built-in Substring() method works great for extracting characters from the beginning of a string, getting characters from the end requires some additional techniques.
Extracting from the end is particularly useful when:
- Working with file extensions
- Processing fixed-length data where important information is at the end
- Handling timestamps or version numbers that appear at the end of strings
Let’s dive into the methods I use regularly.
Method 1 – Using Negative Index with Array Notation
PowerShell 3.0 and later allows you to use negative indexes with array notation, making it easy to access characters from the end of a string.
$string = "PowerShell is awesome!"
$lastFive = $string[-5..-1] -join ''
Write-Output $lastFiveOutput:
some!You can see the exact output in the screenshot below:

Here’s how this works:
- The
-5..-1creates a range that starts at the 5th character from the end and goes to the last character - PowerShell returns these characters as an array of characters
- We join them back together with
-join ''
This method is my go-to for quick substring operations from the end.
Check out How to Join an Array of Strings in PowerShell
Method 2 – Using String Length with the Substring Method
The traditional Substring() method can be used to extract characters from the end by calculating the starting position from the string length.
$string = "PowerShell is awesome!"
$lastFive = $string.Substring($string.Length - 5, 5)
Write-Output $lastFiveOutput:
some!This method:
- Uses
$string.Length - 5to find the position 5 characters from the end - Extracts 5 characters from that position
I find this approach particularly useful when I need precise control over the extraction.
You can see the exact output in the screenshot below:

Read Convert String to Number with Decimal in PowerShell
Method 3 – Using Regular Expressions
Regular expressions provide a powerful way to extract substrings from the end of a string, especially when you need pattern matching.
$string = "John_Smith_12345.docx"
$lastFiveBeforeDot = [regex]::Match($string, '(\w{5})\.').Groups[1].Value
Write-Output $lastFiveBeforeDotOutput:
12345In this example:
- The regular expression
(\w{5})\.matches exactly 5 word characters before a dot - We extract the captured group with
.Groups[1].Value
Regular expressions are my preference when I need complex pattern matching along with substring extraction.
Method 4 – Using the Split Method
The Split() method can be combined with array indexing to extract portions from the end of a string:
$filename = "quarterly-report-2026-Q3.xlsx"
$parts = $filename.Split('-')
$lastPart = $parts[-1] # Gets the last element
Write-Output $lastPartOutput:
Q3.xlsxYou can see the exact output in the screenshot below:

This method works great when:
- Your string has a consistent delimiter
- You need the last segment of a delimited string
I frequently use this approach when parsing log files or CSV data.
Check out PowerShell: Convert Hashtable to String
Method 5 – Using PowerShell’s Right Function (Emulated)
Unlike some other languages, PowerShell doesn’t have a built-in Right() function, but we can easily create one:
function Get-Right {
param(
[string]$string,
[int]$count
)
return $string.Substring([Math]::Max(0, $string.Length - $count))
}
$string = "PowerShell is awesome!"
$lastSeven = Get-Right -string $string -count 7
Write-Output $lastSevenOutput:
awesome!This function:
- Takes a string and count parameter
- Uses
Math.Maxto prevent negative indexes if the count is larger than the string - Returns the desired substring from the end
I’ve added this function to my PowerShell profile since I use it so frequently.
Check out Convert Number to String in PowerShell
Real-World Examples
Now, let me show you some real examples.
Example 1: Extracting File Extensions
One common use case is extracting file extensions:
$files = @(
"budget-2026.xlsx",
"presentation.pptx",
"notes.txt"
)
foreach ($file in $files) {
$extension = $file.Substring($file.LastIndexOf('.') + 1)
Write-Output "File: $file, Extension: $extension"
}Output:
File: budget-2026.xlsx, Extension: xlsx
File: presentation.pptx, Extension: pptx
File: notes.txt, Extension: txtExample 2: Processing Social Security Numbers
When working with sensitive data like SSNs, you might need to extract just the last 4 digits:
$ssn = "123-45-6789"
$lastFour = $ssn.Substring($ssn.Length - 4)
Write-Output "SSN ending in: $lastFour"Output:
SSN ending in: 6789Example 3: Working with Version Numbers
Version numbers often need specific parts extracted:
$versions = @(
"app-1.2.345",
"service-2.4.567",
"api-3.0.789"
)
foreach ($version in $versions) {
$buildNumber = $version.Split('.')[-1]
Write-Output "Version: $version, Build: $buildNumber"
}Output:
Version: app-1.2.345, Build: 345
Version: service-2.4.567, Build: 567
Version: api-3.0.789, Build: 789Performance Considerations
When working with large strings or processing many strings in a loop, performance matters. Here’s a quick comparison of the methods:
| Method | Strengths | Weaknesses |
|---|---|---|
| Negative Index | Simple, readable | Only in PS 3.0+ |
| Substring | Works in all PS versions | Requires length calculation |
| Regex | Powerful pattern matching | More complex, slower |
| Split | Good for delimited strings | Less precise |
| Custom Function | Reusable | Adds function overhead |
For maximum performance when processing thousands of strings, the Substring() method typically offers the best balance of speed and compatibility.
Check out Find Strings in PowerShell Hash Tables
Common Errors and How to Avoid Them
Now, let me show you a few errors you might encounter and how to avoid them.
Error 1: Index Out of Range
$shortString = "Hi"
$lastFive = $shortString.Substring($shortString.Length - 5, 5)
# This will cause an errorSolution: Always check the string length before extracting:
$shortString = "Hi"
$count = 5
if ($shortString.Length -ge $count) {
$lastFive = $shortString.Substring($shortString.Length - $count, $count)
} else {
$lastFive = $shortString
}
Write-Output $lastFiveError 2: Incorrect Regular Expression
$string = "filename.txt"
$pattern = "(\d{5})\." # Expects 5 digits before a dot
$match = [regex]::Match($string, $pattern)
# $match.Success will be falseSolution: Test your regex patterns with sample data and add error handling:
$string = "filename.txt"
$pattern = "(\d{5})\."
$match = [regex]::Match($string, $pattern)
if ($match.Success) {
Write-Output $match.Groups[1].Value
} else {
Write-Output "Pattern not found in string"
}Conclusion
I hope you understand how to extract substrings from the end of a string in PowerShell.
For instance, combining substring extraction with string replacement, case conversion, or string formatting can handle complex text processing tasks with just a few lines of code.
I hope you found these techniques helpful.
You may also like the following tutorials:
- How to Find Dates in Strings with PowerShell?
- PowerShell New Line in String
- PowerShell Convert Byte Array to Hex String
Bijay Kumar is an esteemed author and the mind behind PowerShellFAQs.com, where he shares his extensive knowledge and expertise in PowerShell, with a particular focus on SharePoint projects. Recognized for his contributions to the tech community, Bijay has been honored with the prestigious Microsoft MVP award. With over 15 years of experience in the software industry, he has a rich professional background, having worked with industry giants such as HP and TCS. His insights and guidance have made him a respected figure in the world of software development and administration. Read more.