How do I Find the Position of Substring in PowerShell After Position x?

PowerShell offers support for the execution of the “String” data type. The term string refers to a collection of words that make a meaningful text. It is defined inside the PowerShell within double and single quotes. A string contains a substring, the combination of two or more words within a string. More specifically, the position of the substring can be determined using some specific commands in PowerShell.

This post will illustrate multiple methods to get the substring’s position.

How to Find/Get the Position of the Substring After Position x in PowerShell?

These are the method that can be utilized for finding the position of the selected substring:

Method 1: Use the “IndexOf()” Method to Find the Position of the Substring in PowerShell

The “IndexOf()” method is used in PowerShell to get the specified string’s first occurrence. The count in the “IndexOf()” method starts from zero. For instance, overview the mentioned example.


This example will get the string’s position in PowerShell using the “IndexOf()” method:

> $str = "This is Linux Hint Portal"

> $str.IndexOf("Linux")

In the above-mentioned code:

  • First, we have assigned a string to a variable “$str”.
  • After that, invoke the “IndexOf()” method and pass a substring within inverted commas:

It can be observed that the position of the substring after an x position has been found.

Method 2: Use the “LastIndexOf()” Method to Find the Position of the Substring in PowerShell

Another approach that is relevant to the above method is the “LastIndexOf()”. The “LastIndexOf()” method or function is utilized to retrieve the count of the provided string in PowerShell. For instance, go through the mentioned example below.


This example will demonstrate to count the last occurrence of the string using the “LastIndexOf()” method:

> $str = "Linux Hint is a web portal"

> $str.LastIndexOf("Hint")

In the above code, we called the “LastIndexOf()” method and passed the substring inside it:

As you can see, the count of the last occurrence of the mentioned substring has been displayed in the output.


To find the position of the substring in PowerShell, two methods can be utilized, including “IndexOf()” and “LastIndexOf()”. Both methods use substrings inside their parentheses to find out the position of the substring. This tutorial has presented a detailed procedure to find the position of the substring in PowerShell.

About the author

Muhammad Farhan

I am a Computer Science graduate and now a technical writer who loves to provide the easiest solutions to the most difficult problems related to Windows, Linux, and Web designing. My love for Computer Science emerges every day because of its ease in our everyday life.