Powershell

PowerShell and the -contains operator

PowerShell has a set of containment operators that is considered equal to the equality operator in terms of functionality. There are two types of containment operators, which are “-contains” and “-Noncontains”. The “-contains” operator is used to find the referenced value inside the collection of values. This operator always returns a boolean value such as “True” or “False”, regardless of the input given.

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:

function ContainsOp {
    $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:

function ContainsOp {
    $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.

About the author

Muhammad Farhan

I am a Computer Science graduate and now a technical writer who loves to provide the easiest solutions to the most difficult problems related to Windows, Linux, and Web designing. My love for Computer Science emerges every day because of its ease in our everyday life.