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