InStr


Definition: Returns the position of the first occurrence of one string within another.

 

The InStr function is primarily used to determine whether a specific character or set of characters can be found in a string. In Windows PowerShell you can test for the existence of a substring by using the Contains() method. For example, here we assign the word wombat to a variable named $a, then use Contains() to determine whether or not the letter m appears anywhere in that string. In turn, our True/False return value is stored in the variable $b:

 

$a = "wombat"
$b = $a.contains("m")

 

When you run this command and then echo back the value of $b you should get the following:

 

True

 

What if we used this command:

 

$b = $a.contains("x")

 

That’s right: Windows PowerShell would report back False, because there is no x in wombat.

 

And no i in team.

 

Confession time: The InStr function is typically used to determine whether a specified substring exists in a parent string; most of the time script writers only care whether or not the substring can be found. Technically, though, InStr doesn’t return a Boolean value (that is, True/False); instead, it returns the character position of the first instance of the substring. If that’s what you’d really like to do you can use the IndexOf() method instead of the Contains()method. For example, consider these two lines of code:

 

$a = "wombat"
$b = $a.indexof("m")

 

If you run these two lines of code and then echo back the value of $b, you’ll get back this:

 

2

 

Why? Because the letter m is found in the third character position in wombat. (Yes, we know. But the first character occupies position 0, meaning the second character occupies position 1 and the third character occupies position 2). If the letter m could not be found in the string then a -1 would be returned.