Wednesday, 24 August 2016

Powershell - Check If String Contains Word

We can use the powershell's like operator with wildcard character to check if a string contains a word or another string with case-sensitive and case-insensitive.
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
The following method is used to check if a string contains a word using like operator. By default like operator ignore the case-sensitive check.
$strVal ='Hello world'
if($strVal -like '*World*') {
      Write-Host 'Your string contains the word world'
} else {
      Write-Host 'Your string does not contains the word world'
}
To perform a Case-Sensitive comparison just prefix the word "c" with like operator ("clike").
$strVal ='Hello world'
if($strVal -clike '*world*') {
      Write-Host 'True'
} else {
      Write-Host 'False'
}
We can also use the built in .NET string extension function Contains to check whether a string contains a another string.
$strVal ='Hello world'
if($strVal.Contains('world')) {
     Write-Host 'True'
} else {
     Write-Host 'False'
}
The .Contains() function is case sensitive. If you want to use the Contains() method for case-insensitive check, convert both strings to one case before compare.
$strVal ='Hello world'
if($strVal.ToLower().Contains('world'.ToLower())) {
     Write-Host 'True'
} else {
     Write-Host 'False'
}

Advertisements
Advertisements

No comments:

Post a Comment