IndexOf and LastIndexOf

The IndexOf and LastIndexOf may be used to locate a character or string within a string. IndexOf finds the first occurrence of a string, LastIndexOf finds the last occurrence of the string. In both cases, the zero-based index of the start of the string is returned. If the character, or string, is not present, the two methods will return -1:

$string = 'abcdefedcba' 
$string.IndexOf('b')     # Returns 1 
$string.LastIndexOf('b') # Returns 9 
$string.IndexOf('ed')    # Returns 6 

As -1 is used to indicate that the value is absent, the method is not suitable for statements based on an implicit Boolean. The index 0, a valid position, is considered to be false. The following example correctly handles the return value from IndexOf ...

Get Mastering Windows PowerShell Scripting - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.