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
1 2 |
$Name = "John", "Ray Matt", "Anthony" $Name -Contains "Ray Matt" |
OUTPUT
1 |
True |
Example: 2
-Contains requires exact equality
1 2 |
$Name = "John", "Ray Matt", "Anthony" $Name -Contains "Ray" |
OUTPUT
1 |
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:
1 2 |
$Name = "John", "Ray Matt", "Anthony" $Name -notContains "Ray" |
OUTPUT
1 |
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
1 2 |
$Name = "John", "Ray Matt", "Anthony" "Ray" -in $Name |
Output:
1 |
False |
Example: 2
1 2 |
$Name = "John", "Ray Matt", "Anthony" "Ray Matt" -in $Name |
Output:
1 |
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
1 2 |
$Name = "John", "Ray Matt", "Anthony" "Ray" -in $Name |
Output:
1 |
True |
Example: 2
1 2 |
$Name = "John", "Ray Matt", "Anthony" "Ray Matt" -in $Name |
Output:
1 |
False |
Hey –
Last example is -notin but the demos show -in (likely from previous example). Great examples though! I’ve wondered about those operators for some time! Thanks