PowerShell Substring From End [Extract Text From the End of a String]

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 $lastFive

Output:

some!

You can see the exact output in the screenshot below:

PowerShell Substring From End

Here’s how this works:

  1. The -5..-1 creates a range that starts at the 5th character from the end and goes to the last character
  2. PowerShell returns these characters as an array of characters
  3. 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 $lastFive

Output:

some!

This method:

  1. Uses $string.Length - 5 to find the position 5 characters from the end
  2. 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:

PowerShell Substring From End using Substring Method

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 $lastFiveBeforeDot

Output:

12345

In this example:

  1. The regular expression (\w{5})\. matches exactly 5 word characters before a dot
  2. 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 $lastPart

Output:

Q3.xlsx

You can see the exact output in the screenshot below:

PowerShell Substring From End using split method

This method works great when:

  1. Your string has a consistent delimiter
  2. 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 $lastSeven

Output:

awesome!

This function:

  1. Takes a string and count parameter
  2. Uses Math.Max to prevent negative indexes if the count is larger than the string
  3. 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: txt

Example 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: 6789

Example 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: 789

Performance Considerations

When working with large strings or processing many strings in a loop, performance matters. Here’s a quick comparison of the methods:

MethodStrengthsWeaknesses
Negative IndexSimple, readableOnly in PS 3.0+
SubstringWorks in all PS versionsRequires length calculation
RegexPowerful pattern matchingMore complex, slower
SplitGood for delimited stringsLess precise
Custom FunctionReusableAdds 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 error

Solution: 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 $lastFive

Error 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 false

Solution: 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:

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.