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' }
hi
how can I replace World once it is found?
if($strVal -like ‘*World*’) {
Write-Host ‘Your string contains the word world’
You can use the ‘replace’ operator to replace a part of string text with another text.
$strVal =’Hello world’
$output =”
if($strVal.Contains(‘world’)) {
$output = $strVal -replace ‘world’,’new world’
} else {
$output = $strVal
}
Write-Host $output