- Powershell If String Contains Text
- Powershell Check If String Contains Text
- Powershell Check List Contains
- Powershell If File Contains String Do Action
- Powershell Where String Contains
How can you check if a PowerShell string contains a character or substring?
We can use the comparison operator like with wildcard character to check if a property of object contains a specific string. Note: You can not use the comparison operator contains to check the contains string, because it’s designed to tell you if a collection of objects includes (‘contains’) a particular object. I have a 1st text file looks like this: 12AB34.US. The second text file is CD34EF. I want to find my 2nd text file exist or not in the 1st text file. I tried to cut 3 characters last in the first text file (.US). Then I split to each 2 characters (because the 2nd text file consist of 2 characters).
You might be tempted to try this:
PS> $s = ‘abcdefghijk’
PS> $s -contains ‘f’
False
But –contains is for working with the contents of arrays. So you could do this:
PS> ($s.ToCharArray()) -contains ‘f’
True
You’re implicitly converting the string ‘f’ to [char] to make the comparison. Your comparison is actually this
PS> ($s.ToCharArray()) -contains [char]’f’
True
That’s fine for a single character but if you want to test a substring
PS> $s -contains ‘def’
False
PS> ($s.ToCharArray()) -contains ‘def’
False
That approach won’t work.
You need to use the Indexof method
PS> $s.Indexof(‘f’)
5
PS> $s.Indexof(‘def’)
3
The value returned is the position of the FIRST character in the substring.
Powershell If String Contains Text
You can also test an an array of characters
Powershell Check If String Contains Text
PS> $a = ‘g’,’j’,’a’
PS> $s.IndexOfAny($a)
0
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
abcdefghijkabcdefghijkabcdefghijk
Powershell Check List Contains
You also have the option of picking the LAST occurrence of the substring
PS> $s.LastIndexOf(‘f’)
27
PS> $s.LastIndexOfAny($a)
31
Powershell If File Contains String Do Action
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
Powershell Where String Contains
PS> $s.IndexOf(‘z’)
-1
PS> $s.LastIndexOf(‘z’)
-1