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. You will get this kind of requirement when parsing log files, manipulating file names, processing data from APIs, etc.

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!

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 ''

Here is the exact output in the screenshot below. You can see after I executed the above PowerShell script:

PowerShell Substring From End

This method is my go-to for quick substring operations from the end.

Check out Split Comma Separated String To Array 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

You can see the exact output in the screenshot below:

PowerShell Substring From End examples

I find this approach particularly useful when I need precise control over the extraction.

Check out String Starts With 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

I prefer Regular expressions when I need complex pattern matching and substring extraction.

Method 4 – Using the Split Method

The Split() method in PowerShell can be combined with array indexing to extract portions from the end of a string:

$filename = "quarterly-report-2025-Q3.xlsx"
$parts = $filename.Split('-')
$lastPart = $parts[-1]  # Gets the last element
Write-Output $lastPart

Output:

Q3.xlsx

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 Replace Carriage Returns in Strings Using PowerShell

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 8
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

You can see the exact output in the screenshot below:

Substring From End in PowerShell

I’ve added this function to my PowerShell profile since I use it so frequently.

Read Check if a File Exists and Rename it Using PowerShell

PowerShell Substring From End: Real-World Examples

Now, let me show you some real examples of PowerShell substring from the end.

Example 1: Extract File Extensions

In the first example, I will show you how to extract file extensions from file names using PowerShell.

$files = @(
    "budget-2025.xlsx",
    "presentation.pptx",
    "notes.txt"
)

foreach ($file in $files) {
    $extension = $file.Substring($file.LastIndexOf('.') + 1)
    Write-Output "File: $file, Extension: $extension"
}

Output:

File: budget-2025.xlsx, Extension: xlsx
File: presentation.pptx, Extension: pptx
File: notes.txt, Extension: txt

You can see the exact output in the screenshot below:

PowerShell Substring From End example

Example 2: Process Social Security Numbers

When working with sensitive data like SSNs, you might need to extract just the last four digits. Here is a complete PowerShell script to get the last four digits of a Social Security number.

$ssn = "123-45-6789"
$lastFour = $ssn.Substring($ssn.Length - 4)
Write-Output "SSN ending in: $lastFour"

Output:

SSN ending in: 6789

Example 3: Work 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

Check out Split a String by Length in PowerShell

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.

Common Errors and How to Avoid Them

Now let me show you some of the common errors that you might get while working with this, and also I will show you how to avoid these errors.

Error 1: Index Out of Range

The first error you might receive is the index out of range in PowerShell.

$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

Now I hope you understand how to extract substrings from the end of a string using PowerShell. I hope you found these techniques helpful. Do let me know if you have any questions in the comments below.

You may also like:

Power Apps functions free pdf

30 Power Apps Functions

This free guide walks you through the 30 most-used Power Apps functions with real business examples, exact syntax, and results you can see.

Download User registration canvas app

DOWNLOAD USER REGISTRATION POWER APPS CANVAS APP

Download a fully functional Power Apps Canvas App (with Power Automate): User Registration App