PowerShell for Windows Admins

Aug 31 2018   6:05AM GMT

PowerShell string contains

Richard Siddaway Richard Siddaway Profile: Richard Siddaway


How can you check if a PowerShell string contains a character or substring?

You might be tempted to try this:

PS> $s = ‘abcdefghijk’
PS> $s -contains ‘f’

But –contains is for working with the contents of arrays. So you could do this:

PS> ($s.ToCharArray()) -contains ‘f’

You’re implicitly converting the string ‘f’ to [char] to make the comparison. Your comparison is actually this

PS> ($s.ToCharArray()) -contains [char]’f’

That’s fine for a single character but if you want to test a substring

PS> $s -contains ‘def’
PS> ($s.ToCharArray()) -contains ‘def’

That approach won’t work.

You need to use the Indexof method

PS> $s.Indexof(‘f’)
PS> $s.Indexof(‘def’)

The value returned is the position of the FIRST character in the substring.

You can also test an an array of characters

PS> $a = ‘g’,’j’,’a’
PS> $s.IndexOfAny($a)

Again you get the FIRST character in this case the ‘a’

Remember PowerShell is .NET based so the first index is 0

Lets get some repetition into our target

PS> $s = $s * 3

PS> $s

You also have the option of picking the LAST occurrence of the substring

PS> $s.LastIndexOf(‘f’)

PS> $s.LastIndexOfAny($a)

This last one is the last ‘j’ in the string – its the last occurrence of any of the characters you wanted to match.

If there isn’t a match you get –1 returned

PS> $s.IndexOf(‘z’)
PS> $s.LastIndexOf(‘z’)

 Comment on this Post

There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: