How to check if the string contains the specific word?

PowerShellMicrosoft TechnologiesSoftware & Coding

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
raja
Published on 08-Feb-2021 07:54:10
Advertisements