Power Shell Containment Operators
The containment operators (-contains and -notcontains) are similar to the equal operators. However, the containment operators always return a Boolean value, even when the input is a collection. The conditional operator -Contains is similar to -eq, except it returns ‘True’ or ‘False’. -Contains is designed for situations where you wish to test for one particular item in a collection, array or a hash table.
Operators |
Description |
-contains |
Returns true when reference value contained in a collection |
-notcontains |
Returns true when reference value not contained in a collection |
-in |
Returns true when test value contained in a collection |
-notin |
Returns true when test value not contained in a collection |
–contains
Always returns a Boolean value. Returns TRUE only when the test value exactly matches at least one of the reference values. When the test value is a collection, the Contains operator uses reference equality. It returns TRUE only when one of the reference values is the same instance of the test value object.
Syntax: <Reference-values> -contains <Test-value>
Example: 1
Contains checks each item between the commas
$Name = "John", "Ray Matt", "Anthony"
$Name -Contains "Ray Matt"
OUTPUT
True
Example: 2
-Contains requires exact equality
$Name = "John", "Ray Matt", "Anthony"
$Name -Contains "Ray"
OUTPUT
False
-notcontains
The negative -NotContains is not as useful as -NotMatch. However, from what we have already learned the syntax is predictable.
Syntax: <Reference-values> -notcontains <Test-value>
Example:
$Name = "John", "Ray Matt", "Anthony"
$Name -notContains "Ray"
OUTPUT
True
-in Operator
In operator return the boolean value if the test value appears in a collection of reference values. Always return as Boolean value. Returns TRUE only when the test value exactly matches at least one of the reference values else it will returns FALSE.
Syntax: <Test-value> -in <Reference-values>
Example: 1
$Name = "John", "Ray Matt", "Anthony"
"Ray" -in $Name
Output:
False
Example: 2
$Name = "John", "Ray Matt", "Anthony"
"Ray Matt" -in $Name
Output:
True
-notin Operator
In operator return the boolean value if the test value appears in a collection of reference values. Always return as Boolean value. Returns TRUE only when the test value not a exactly matches at least one of the reference values else it will returns FALSE.
Syntax: <Test-value> -notin \<Reference-values>
Example: 1
$Name = "John", "Ray Matt", "Anthony"
"Ray" -in $Name
Output:
True
Example: 2
$Name = "John", "Ray Matt", "Anthony"
"Ray Matt" -in $Name
Output:
False