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 in a conditional statement:
$string = 'abcdef' if ($string.IndexOf('a') -gt -1) {
'The string contains an a' }
The scope of the IndexOf and LastIndexOf methods can be limited using the start index and count arguments.
Methods that are able to locate a position within a string are useful when combined with other string methods:
PS> $string = 'First,Second,Third'
$string.Substring(
$string.IndexOf(',') + 1, # startIndex (6)
$string.LastIndexOf(',') - $string.IndexOf(',') - 1 # length (6)
)
Second