Check If a String Contains a Specific Word



To check if the PowerShell string contains a specific word, we can use the string method Contains(). For example,

Example

PS C:\> $str = 'TestNZ01LT'
PS C:\> $str.Contains('NZ')
True

Now the funny thing is, even if the PowerShell is case-Insensitive, the above command is not. We need to provide the exact substring. For example, the below output will be false.

Example

PS C:\> $str.Contains('Nz')
False

To overcome this problem, we can either provide the same search name in the method or we need to use the lowercase or uppercase method if you don’t want the search case-sensitive.

PS C:\> $str = 'TestNZ01LT'
PS C:\> ($str.ToLower()).Contains(('Nz').ToLower())
True
PS C:\> ($str.ToUpper()).Contains(('Nz').ToUpper())
True
Updated on: 2021-02-08T07:55:01+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements