Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
0 like 0 dislike
1.4k views
in PowerShell by 37 41 48

I am trying to check if a specific string contains a certain word in PowerShell but when I used the -Contains operator it returns a wrong result although the string contains this word!

$string = "he will update the file"

if($string -contains "file")
{
Write-Host "True"
}
else {Write-Host "False" -ForegroundColor Red
}

Why contains operator doesn't work with string value and How can I use contains in PowerShell?


1 Answer

1 like 0 dislike
by 159 198 381
selected by
 
Best answer

How to use Contains in PowerShell?

First, you should know that the -Contains operator is not used to matching a substring in PowerShell, instead you have to use the Contains() function to check if your string contains a specific word as below:

if ($string.Contains("file")) { 
  Write-host "True"
}

Note: The Contains function is case sensitive, so it would be a great idea to convert your string to lower case as below:

if ($string.ToLower().Contains("file")) { 
  Write-host "True"
}

Using -Contains operator in PowerShell

As per PowerSHell Documentation, the -contains operator is used to check if a collection of values includes a single test value.

Ex:

Consider you have an array in PowerShell as below

$products= "Office365","SharePoint","PowerShell"

And you need to check if this array has a 'Powershell', in this case, you have to use -Contains operator in PowerShell as below

if ($products -contains "Powershell") { 
  Write-host "True"
}
by 37 41 48
0 0
It's very clear now, Thanks alot!
If you don’t ask, the answer is always NO!
...