How to Extract a Substring in PowerShell

  1. Use the Substring() Method to Extract a Substring in PowerShell
  2. Dynamically Finding a Substring Using the Length Method in PowerShell
How to Extract a Substring in PowerShell

A typical scenario as a Windows administrator is to figure out a way to find a particular snippet of text inside a string called the substring. Windows PowerShell makes finding a substring easy.

The article will discuss efficiently extracting a substring in a string using PowerShell’s string library.

Use the Substring() Method to Extract a Substring in PowerShell

We can use the Substring() method to find a string inside a string. For example, perhaps we have a string like 'Hello World is in here Hello World!' and you’d like to find the first four characters.

Example Code:

$sampleString = 'Hello World is in here Hello World!'
$sampleString.Substring(0, 5)

Output:

Hello

The first argument to pass in the Substring() method is the position of the leftmost character, which is 'H'. The second argument to pass is the farthest rightmost character position, which is the space character.

The Substring() method returns all the characters preceding the character position in the second character.

Dynamically Finding a Substring Using the Length Method in PowerShell

Using the string $sampleID = 'John_Marc_2021' and you want to find the last four characters, instead of doing something like the example below.

Example Code:

$sampleID = 'John_Marc_2021'
$sampleID.SubString(0, 4)

Output:

John

We can replace 0 with $sampleID.Length - 4 argument, and we don’t need to provide the second argument. The Length string method returns the position of the last character.

Using the Length method of the string, which is the total number of characters in the given string, and deducting from that count, allows us to pick out substrings dynamically.

Example Code:

$sampleID = 'John_Marc_2021'
$sampleID.SubString($sampleID.Length - 4) # The - 4 in the expression will subtract the Length of the substring.

Output:

2021

The PowerShell substring method will always default to the last character position if we don’t specify the end position.

Marion Paul Kenneth Mendoza avatar Marion Paul Kenneth Mendoza avatar

Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.

LinkedIn

Related Article - PowerShell String