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.
Example
This example will get the string’s position in PowerShell using the “IndexOf()” method:
> $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.
Example
This example will demonstrate to count the last occurrence of the string using the “LastIndexOf()” method:
> $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.
Conclusion
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.