How to Substring in PowerShell?

Working with Substrings in PowerShell is a very common requirement when manipulating strings. Most of the time, I am required to get a substring of a string. In this PowerShell tutorial, I will explain how to substring in PowerShell and how to use the substring() method in PowerShell with various examples.

To substring in PowerShell using the Substring() method, you need to specify the starting index and optionally the length of the substring. The syntax is $string.Substring(startIndex, length), where startIndex is the zero-based position where the substring begins, and length is the number of characters to extract. For example, to extract “York” from “New York City”, you would use $string.Substring(4, 4). If the length is omitted, the substring extends to the end of the string.

A substring is a portion of a string. For example, in the string “New York City”, “New York” is a substring. PowerShell provides several methods to extract substrings from strings.

Note: I used Visual Studio Code to execute all the PowerShell scripts, but you can use any other editor like Windows PowerShell ISE.

1. PowerShell Substring() Method

The Substring() method in PowerShell extracts a portion of a string based on a starting index and an optional length. The starting index specifies the position in the string where extraction should begin, and the length determines how many characters to include.

Syntax

$string.Substring(startIndex, [length])
  • startIndex: The zero-based starting character position of the substring.
  • length: (Optional) The number of characters in the substring. If omitted, the substring continues to the end of the string.

Example-1: Extract a Substring from a String

Let’s consider a string representing a full address: “123 Main Street, Los Angeles, CA 90001”. We want to extract the city name “Los Angeles”.

Here is the complete script of using substring() method to extract a substring from a string in PowerShell.

$address = "123 Main Street, Los Angeles, CA 90001"
$cityStartIndex = $address.IndexOf(",") + 2
$cityEndIndex = $address.IndexOf(",", $cityStartIndex)
$city = $address.Substring($cityStartIndex, $cityEndIndex - $cityStartIndex)
Write-Output $city

In this example, we find the starting index of the city by locating the first comma and adding 2 (to skip the comma and space). Then, we find the next comma to determine the end of the city name. Finally, we extract the substring using these indices.

I executed the above script using VS code, and you can see the output in the screenshot below:

substring in PowerShell

Example-2: Get Leftmost and Rightmost Characters using Substring() method

Here is another example of how to get the leftmost and rightmost characters using the Substring() method in PowerShell.

To extract the leftmost characters from a string in PowerShell, you can use the Substring() method. Suppose you have the string "PowerShell", and you want to extract the first four characters. You can achieve this with the following command:

$string = "PowerShell"
$leftmost = $string.Substring(0, 4)

This script extracts the characters starting from position 0 up to 4, resulting in "Powe".

Using the Substring() method in PowerShell, you can also get the rightmost characters of a string. For instance, if you need the last four characters of the string "PowerShell", you can use:

$string = "PowerShell"
$rightmost = $string.Substring($string.Length - 4)

This script captures "hell" by starting the extraction from four characters before the end of the string.

Similarly, if you want to extract extensions from filenames, you can use the substring method like below:

$filename = "report2024.pdf"
$extension = $filename.Substring($filename.Length - 3)

This would result in "pdf".

Example-3: Extract File Extension

Let me show you another example of how to use the Substring () method in PowerShell to extract a file extension from a file name.

Let’s say you have a string representing a file name: “document.pdf”. We want to extract the file extension “pdf”.

$fileName = "document.pdf"
$fileExtension = $fileName.Substring($fileName.LastIndexOf(".") + 1)
Write-Output $fileExtension

In this example, we use the LastIndexOf method to find the position of the last period in the file name and then use Substring to extract the file extension.

The screenshot below shows the output after I executed the above script using VS code. It is returning me the file extension (.pdf).

PowerShell substring method

Read Get File Name Without Extension in PowerShell

2. Substring using the Split() Method in PowerShell

Now, let me show you another method: the split method to extract a substring from a string in PowerShell.

The PowerShell split() method splits a string into an array based on a delimiter.

Syntax

$string.Split([separator], [count], [options])
  • separator: The character(s) to split the string on.
  • count: (Optional) The maximum number of substrings to return.
  • options: (Optional) StringSplitOptions to remove empty entries.

Example-1: Extract Substring using Split() method

Consider a string representing a full name: “John F. Kennedy”. We want to split this into first, middle, and last names.

Below is the complete PowerShell script.

$fullName = "John F. Kennedy"
$nameParts = $fullName.Split(" ")
$firstName = $nameParts[0]
$middleName = $nameParts[1]
$lastName = $nameParts[2]
Write-Output $firstName   # Output: John
Write-Output $middleName  # Output: F.
Write-Output $lastName    # Output: Kennedy

In this example, we split the full name by spaces and then access each part using array indices.

Example-2: Extract Domain from an Email Address

Let me show you another example of how to use the split() method for substring in PowerShell.

Consider a string representing an email address: “john.doe@powershellfaqs.com”. We want to extract the domain “powershellfaqs.com”.

Then, you can use the below PowerShell script.

$email = "john.doe@powershellfaqs.com"
$domain = $email.Split("@")[1]
Write-Output $domain

In this example, we use the Split method to divide the email address at the “@” character and then access the second part of the split string to get the domain.

Look at the screenshot below; it is showing the domain name. I executed the above script using VS code.

PowerShell Extract Substring using Split method

Read Split Strings by Newlines in PowerShell

3. Substring Using Regular Expressions in PowerShell

Regular expressions are very useful in PowerShell. Let me show you how to use regular expressions to substring.

Syntax

Here is the syntax:

[regex]::Matches($string, $pattern)
  • $string: The input string.
  • $pattern: The regular expression pattern.

Example-1: Extract ZIP Code using regular expressions

Consider the same address string: “123 Main Street, Los Angeles, CA 90001”. We want to extract the ZIP code. For that, we can use the regular expressions in PowerShell. Here is the complete script.

$address = "123 Main Street, Los Angeles, CA 90001"
$zipCodePattern = "\d{5}"
$zipCode = [regex]::Match($address, $zipCodePattern).Value
Write-Output $zipCode

In this example, we use a regular expression pattern \d{5} to match a five-digit ZIP code. This is how you can use regular expressions to substring in PowerShell.

I executed the above PowerShell script using Visual Studio Code, and you can see the output in the screenshot below:

how to substring in PowerShell

Read Split a String by Word in PowerShell

4. Substring Using Select-String Cmdlet

Here is another method to substring in PowerShell: using the Select-String cmdlet.

The Select-String cmdlet in PowerShell can also be used to search for patterns in strings and extract substrings.

Syntax

Here is the syntax of the Select-String cmdlet.

Select-String -InputObject $string -Pattern $pattern
  • -InputObject: The input string.
  • -Pattern: The pattern to search for.

Example-1: Extract State Abbreviation

Consider the same address string: “123 Main Street, Los Angeles, CA 90001”. We want to extract the state abbreviation “CA”.

Below is the PowerShell script for substring using Select-string.

$address = "123 Main Street, Los Angeles, CA 90001"
$statePattern = "\b[A-Z]{2}\b"
$state = (Select-String -InputObject $address -Pattern $statePattern).Matches.Value
Write-Output $state  # Output: CA

In this example, we use a regular expression pattern \b[A-Z]{2}\b to match the two-letter state abbreviation.

Conclusion

In this PowerShell tutorial, I have explained different methods to extract substrings in PowerShell, including the Substring() method, Split() method, regular expressions, Select-String cmdlet, and IndexOf and LastIndexOf methods.

I hope you also know now about the substring() method and how to substring in PowerShell.

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.