SoFunction
Updated on 2025-03-03

Example of the IndexOf function that finds string position in PowerShell

This article introduces the use of the IndexOf function of a string in PowerShell to query whether another string exists in a string, and if so, where is it.

The IndexOf function is a static method of a String object that finds the position of a string in another string. If the search string does not exist in the query string, the return value is -1. If present, return the location where the search string is located, starting from 0.

Let's take a look at the example below:

"13" does not exist in "123"

Copy the codeThe code is as follows:
PS C:\Users\spaybow> "123".indexof("13")
-1

In "123", the position of "1" is 0, that is, the starting position.
Copy the codeThe code is as follows:
PS C:\Users\spaybow> "123".indexof("1")
0

In "123", the position of "2" is 1, that is, the second position.
Copy the codeThe code is as follows:
PS C:\Users\spaybow> "123".indexof("2")
1

In "123", the position of "12" is 0, that is, the starting position.
Copy the codeThe code is as follows:
PS C:\Users\spaybow> "123".indexof("12")
0

This article introduces so much about PowerShell using IndexOf function to find string locations. I hope it will be helpful to you. Thank you!