This post will discuss the “-contains” operator and its functionality.
How to Use PowerShell “-contains” Operator?
In PowerShell, the “-contains” operator is used to match the collection of values with the referenced value. If the referenced value is in the collection of values, then the output result will return as “True” otherwise, the resultant output will return as “False”. This operator outputs the result in the boolean form.
Example 1: Using “-contains” Operator for Matching the Referenced Value
In this example, we will match the referenced value with the collection of values stored inside a variable:
$text = "Silly Cat", "Loyal Dog", "Fast Rabbit"
$text -contains "Loyal Dog"
}
ContainsOp
According to the given script:
- First, we have created a function named “ContainsOp”.
- After that, create a collection of strings.
- Then, use the “-contains” operator, along with the value we want to match with the collection.
- Finally, call the function by writing its name outside the curly braces to execute it:
It can be observed that the “-contains” operator output “True” as it located the specified values in the collection of values.
Example 2: Using “-contains” Operator for Matching the Exact Value
In this example code, the “-contains” operator will look for the exact value in the collection of values:
$text = "Silly Cat", "Loyal Dog", "Fast Rabbit"
$text -contains "Loyal"
}
ContainsOp
In the same script, we have now only changed the parameter that is passed to the “-contains” operator for matching with the “$text” string collection:
As you can see the output is “False” because the “-contains” operator did not find the exact value.
Conclusion
PowerShell includes a “-contains” operator that is used to match the given/referenced value in the collection of values stored in a variable. If the values are found inside the collection, then the output will be “True”; otherwise, “False” will be returned. This tutorial has demonstrated complete detail of the “-Contains” operator in PowerShell.