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'
}

Advertisement

2 thoughts on “Powershell – Check If String Contains Word”

  1. hi
    how can I replace World once it is found?

    if($strVal -like ‘*World*’) {
    Write-Host ‘Your string contains the word world’

    Reply
    • 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

      Reply

Leave a Comment