How to Extract a PowerShell Substring From a String

Photo of author

By Victor Ashiedu

Published

I have had multiple occasions when I needed to extract sub-strings from strings in PowerShell scripts. This article is my attempt to share some of my experiences.

Overview

In PowerShell, a substring is a part of a string. You can create a PowerShell substring from a string using either the substring or split methods.

An example of a string is subdomain.domain.com. The substrings of subdomain.domain.com are subdomain, domain, and com.

Option 1: Extract a Substring with the Substring Method

In this first section, you will learn how to extract substrings from a string with the Substring Method.

I am aware that using substrings as part of a string in the same sentence as the Substring Method may be confusing. For the purpose of clarity, “substrings as part of a string” refers to extracting part of a string. For example, extracting the substring, “usa” from the string usa.www.itechguides.com. On the contrary, the Substring Method refers to the PowerShell Substring Method used to perform the task.

I will kick of this section by explaining the syntax of the Substring Method.

Syntax of the PowerShell Substring Method

The Syntax of the Substring Method:

string.substring(int startIndex, int length)

To ensure that you understand the remaining parts of this section, it is extremely important that you pay attention to my explanation of these syntaxes.

As you can see from the syntax, when you specify the Substring Method of a string, you enter startIndex AND length.

The int in the syntax indicates that the startIndex and length are numbers (integers)

The startIndex is the first character of the substring you want to extract (counting from left to right and starting from adding 1 to the result of the IndexOf – except for the first character).

Furthermore, the length is the number of characters you want to extract, starting from 1 and counting from the first character of the substring you want to extract.

In the next section, I will explain the IndexOf Method and how to use it to determine the startIndex and length. If you are still confused by my attempt to explain this fairly complex concept of startIndex and length, don’t be discouraged – it will become clearer as you progress in the guide.

To help you understand this concept, the next section will discuss IndexOf and LastIndexOf Methods.

Step 1: Identify the Position of the Substring

When I explained the syntax of the Substring Method, I said that the startIndex of the PowerShell Substring Method is the first character of the substring you want to extract (determined by adding 1 to the result of the IndexOf value for that substring).

In this section, I will use the IndexOf and LastIndexOf Methods of a PowerShell string to show you how PowerShell determines the positions of substring characters in a string.

To illustrate, let’s examine the index position of the first letter “u” in usa.www.itechguides.com – by running the command below…

"usa.www.itechguides.com".IndexOf('u')
The IndexOf Method finds the first occurrence of a string (counting from left to right and starting from zero)

The result is zero (0)…

Why is this important? Glad you asked!

Do you remember the startIndex AND length in the syntax of the PowerShell Substring Method?

string.substring(int startIndex, int length)

If the index position of the letter “u” in usa.www.itechguides.com is zero (o), according to the IndexOf Method – it means that if we wish to extract characters starting from the letter “u”, our startIndex will be 0 – since it is the first character in the string.

The exception to the rule of adding 1 to the result of IndexOf command to determine the startIndex is the first character in the string. The startIndex of the first character of a string will always be zero (0).

How amazing!

Now, let’s add another layer to this. What if we want to find the last occurrence of a character in a string?

Instead of using, the IndexOf Method, we will use the LastIndexOf Method. This command will determine the location of the last occurrence of the letter “u” in the string, usa.www.itechguides.com:

"usa.www.itechguides.com".LastIndexOf('u')
LastIndexOf finds the last occurrence of the string (counting from left to right and starting from zero)

The result is 14…

Having this knowledge of how PowerShell determines the position of substring characters in a string will help you manipulate PowerShell strings – no matter the complexity.

Step 2 (Example 1): Extract a Substring Left of a String

In this section, you will learn how to extract a substring from the left of a string. I will show you an example that can be used in production environments.

Assuming you manage an Active Directory domain with multiple subdomains. The subdomains are named using a 3 letter country name. Examples of your subdomains are USA.www.itechguides.com, JPN.www.itechguides.com.

Furthermore, let’s assume that you are writing a PowerShell script that requires you to run conditional commands based on the country subdomain name – within you Active Directory domain.

In this section, I will teach you how to extract the subdomain USA, from USA.www.itechguides.com.

Let’s start by saving the subdomain, USA.www.itechguides.com in a variable called subdomain.

$subdomain = "USA.www.itechguides.com"

Follow the steps below to extract USA, from USA.www.itechguides.com:

  1. Enter a period (.) next to the variable the subdomain is saved, followed by the word Substring. Finally, add an opening bracket…
$subdomain.Substring(
After entering Substring, you can also press the Tab key on your keyboard. When you press the Tab key, PowerShell will add the opening bracket (.
  1. Next, enter the startIndex followed by a comma (,). Before you do this, remember we want to extract “USA”. In this instance, since we want to extract from the first character, our startIndex is zero (0). The command will now look like this:
$subdomain.Substring(0,
  1. Finally, enter the length, followed by the closing bracket, ). In this example, the length (counting from the number next to the startIndex) is 3 – the startIndex is 0, adding 1 to 0 gives 1.

    If you count from “U” – “USA” has 3 characters – making the length a total of 3 characters.

    Here is the final script…
$subdomain.Substring(0,3)

To see the command in action, run the command below, first…

$subdomain = "USA.www.itechguides.com"

This saves the string, USA.www.itechguides.com in the PowerShell variable, $subdomain. Then, run the command that extracts the “USA” substring from the string, USA.www.itechguides.com.

$subdomain.Substring(0,3)

As expected, the result is “USA”!

What if you want to extract the parent domain, www.itechguides.com from USA.www.itechguides.com? What will be our startIndex and length?

To determine your startIndex, first run the IndexOf command, using the first period (.) as your input.

$subdomain.IndexOf(".")

The result is 3…

According to my previous explanation, to determine the startIndex from the result of the IndexOf command, add 1. If we add 1 to 3, our startIndex is 4.

Next, to determine the length, start counting from 1, beginning from the first character of the string you want to extract. Then, stop at the last character you want to extract from the string.

Remember that we want to extract www.itechguides.com from USA.www.itechguides.com?

Counting from the first character of the string we want to extract (i), beginning at 1, the length is 15 (www.itechguides.com is 15 characters).

Based on these values, the command that extracts the PowerShell substring, www.itechguides.com from USA.www.itechguides.com is…

$subdomain.Substring(4,19)

Here is the result, www.itechguides.com!

Finally, to help simplify this fairly confusing concept of startIndex, IndexOf, and length, here is a summary:

  1. The startIndex of the first character of a PowerShell string will always be zero (0)
  2. To determine the startIndex of a substring, add 1 to the IndexOf command result
  3. Finally, the length of the PowerShell substring you want to extract is the total number (starting from 1) and counting from the first character of the substring to the last character of the substring.

Step 2 (Example 2): Extract Around a Specified Character

In this section, I will teach you how to extract PowerShell substring before and after a specified character.

To illustrate this, let’s go back to our subdomain…

$subdomain = "USA.www.itechguides.com"

Say I want to extract the substring before ad after the first period (.). Effectively, I want to extract “USA” (the substring before the specified character).

Additionally, I want to extract “www.itechguides.com” (the substring after the specified character).

The first step is to use the IndexOf Method to determine the position of the reference character. The command below saves the position of the reference character in a variable called refcharacter.

$refcharacter = $subdomain.IndexOf(".")

Next, use the substring Method to extract the substring before the reference character.

$subdomain.Substring(0,$refcharacter)

Here is the result…

Finally, use the following PowerShell substring Method to extract the substring after the reference character

$subdomain.Substring($refcharacter+1)

As expected, the result extracts the substring after the period, which is www.itechguides.com!

Step 2 (Example 3): Extract a Substring Between 2 Characters

In this section, I will teach you how to extract “itechguides” from “USA.www.itechguides.com“. In this example, I want to extract a PowerShell substring between 2 characters.

The two characters in this example are the first and last periods (.). The script requires 3 commands.

In the first command, we use the IndexOf Method to determine the position of the first reference character (.). Then, save the result in a variable called firstref.

$firstref = $subdomain.IndexOf(".")

Next, we use the LastIndexOf Method to determine the location of the last reference character. The result is saved in lastref variable.

$lastref = $subdomain.LastIndexOf(".")

Finally, to extract the PowerShell substring, itechguides between 2 characters (the periods), run the command below…

$subdomain.Substring($firstref+1,$lastref-4)

In the command, we added 1 to the result of the IndexOf command. In this example, 3, giving a total of 4.

This makes our startIndex 4.

Additionally, in the PowerShell substring Method, we used the length as $lastref-4.

From our previous commands, $lastref is the variable we saved the result of the LastIndexOf command.

The result is 15. Removing 4 from 15 makes our length 11.

The result from the last command is www.itechguides!

Option 2: Extract Substrings with the Split Method

In the first section of this guide, I discussed how to extract a PowerShell substring with the Substring Method. In this section, you will learn how to extract PowerShell substring with the Split Method.

As usual, I will start this section with the syntax of the PowerShell Split Method.

Syntax of The PowerShell Split Method

The syntax of the Split Method for extracting a PowerShell substring is:

string.Split("delimiter")[substring position]

The delimiter is any character you want to use to split the PowerShell string into individual substrings.

The “substring position” placed in the [] bracket is used to select a specific substring you want to return from the strings.

Example 1: Use Multiple Delimiters with PowerShell Split

As seen in the syntax of the PowerShell Split Method, it allows only one delimiter. However, if you want to split substrings from a string with multiple delimiters, you have to use the PowerShell Split Operator, instead.

The syntax of the PowerShell Split Operator is…

string -Split("delimiter")

If you want to use multiple delimiters, first save the string in a variable – in this example, $string. Then, use the automatic pipeline variable $_ to add the multiple delimiters as shown below:

$string -Split {$_ -eq "delimiter2" -or $_ -eq "delimiter1"}

For example, we can split this Active Directory Distinguished Name, OU=LON,OU=DEV,DC=ITECHGUIDES,DC=COM – using the two delimiters, “=”, and “,”.

First, let’s save the DN in a variable called $ADDN…

$ADDN = "OU=LON,OU=DEV,DC=ITECHGUIDES,DC=COM"

Then, to split the string using the “=”, and “,” delimiters, use the command below:

$ADDN -Split {$_ -eq "=" -or $_ -eq ","}

Bingo, the last command splits the string into individual PowerShell substrings!

In the next section, you will learn how to return one of the substings.

Example 2: Extract a Substring with the Split Method

In the last section, you saw how to split a string into individual substrings using the PowerShell Split Operator. Here is the last command…

$ADDN -Split {$_ -eq "=" -or $_ -eq ","}

The command splits the string into its substrings.

When I discussed the syntax of the Split Method for extracting a PowerShell substring is, I included a [] bracket that contains the position of the substring you want to return:

string.Split("delimiter")[substring position]

PowerShell numbers the positions of substrings from zero (0). So, going back to the Active Directory DN example – see the screenshot below – the first substring “OU” is in position zero (0), “LON” is in position 1, and so on.

So, to return “LON”, we will enclose the last command in the [1] bracket. In this instance, 1 is the position of the substring we want to return.

Here is the command…

($ADDN -Split {$_ -eq "=" -or $_ -eq ","})[1]

Here is the result of the command:

Alternatively, you could save the result of the command with the Split Operator into a variable.

$ADDNSubstrings = $ADDN -Split {$_ -eq "=" -or $_ -eq ","}

Then, return any of the substrings by enclosing the substring position in the [] bracket. For example, to return “LON”, we will use the command below:

$ADDNSubstrings[1]

The result is the same as the previous command without the variable…

Example 3: Extract the Last Element of a Substring with the Split Method

If you want to return the first or last element (character) of a substring, you can use the same principle from our last example.

While researching this topic, I stumbled on this stackoverflow.com thread. The user has a string shown below:

0.3.1-15-g3b885c5
The StackOverflow question explains that the string, 0.3.1-15-g3b885c5 means Tag-CommitDistance-CommitId. So, 0.3.1 is the tag, 15 is the CommitDistance, and g3b885c5 is the CommitId.

The question is to return the first part of the string, 0.3.1 – according to this user, called tag. Additionally, the user wants to return the last part of the string, g3b885c5, called the CommitId.

The first step is to save the string into a variable (this is optional but generally makes life easier).

$Tcc = "0.3.1-15-g3b885c5"

Then, use the Split Method to split the string into PowerShell substrings using “-” as the delimiter. Once again, to make it easy for me to explain, I will save the result in another variable…

$TccSubstrings = $Tcc.split("-")

To see the result of the last command, run the $TccSubstrings variable alone.

$TccSubstrings

Here it is…

Based on our previous examples in this section, to extract the Tag (the first substring), use the command below:

$TccSubstrings[0]

Finally, to extract the CommitId (the last substring), use the command below…

$TccSubstrings[2]

And here are the results…

Note that you can also solve this problem by running a single command…

("0.3.1-15-g3b885c5".split("-"))[0,2]

And here is the same result…

There is no magic to this, all I did was combine all the commands into one command!

Example 4: Split String and Remove Empty Entries

In this final example, I want to show you how to split a string with empty spaces (or entries) into substrings. Then, remove the empty spaces in the final result.

In another stackoverflow.com thread, a user posted this string saved in a variable:

$text = "Video  Video  Audio  Audio  VBI  VBI"

The user then used the Split Method to split the string into individual substrings.

$text.Split()

According to the user (and this is obvious), the problem is that the result has spaces.

The person who posted this question wanted the spaces removed from the substrings. There are multiple solutions but one quick way is to pipe the output of the split command to Where-Object.

This is courtesy of Rynant. Here is the command…

$text.Split() | Where-Object {$_ }

And here is the result…

Conclusion

I have shared two options for splitting substrings from strings in PowerShell. Specifically, I shared how to use the Substring and Split Methods to separate substrings from strings.

As usual, we like to hear your thoughts. If this article meets your expectations, simply click the Yes button in the “Was this page helpful?” question below. However, if it fell short, click No and kindly give us some details so we can get better.

Finally, for more PowerShell tech Itechguides, visit our Windows PowerShell How-To guide page. You may also find our Work from Home page very helpful.

About the Author

Photo of author

Victor Ashiedu

Victor is the founder of InfoPress Media, publishers of Ilifeguides and Itechguides. With 20+ years of experience in IT infrastructure, his expertise spans Windows, Linux, and DevOps. Explore his contributions on Itechguides.com for insightful how-to guides and product reviews.

Related Articles

Get in Touch

We're committed to writing accurate content that informs and educates. To learn more, read our Content Writing Policy, Content Review Policy, Anti-plagiarism Policy, and About Us.

However, if this content does not meet your expectations, kindly reach out to us through one of the following means:

  1. Respond to "Was this page helpful?" above
  2. Leave a comment with the "Leave a Comment" form below
  3. Email us at [email protected] or via the Contact Us page.

Leave a comment

Send this to a friend