PowerShell Basics: Comparison Operators and Conditional Logic

Comparison Operators and Conditional Logic

Comparison operators let you specify conditions for comparing values and finding values that match specified patterns. To use a comparison operator, specify the values that you want to compare together with an operator that separates these values.

Equality

Operators  Description
-eq equals
-ne not equals
-gt greater than
-ge greater than or equal
-lt less than
-le less than or equal



Containment 

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

Matching

Operators Description
-like Returns true when string matches wildcard pattern
-notlike Returns true when string does not match wildcard pattern
-match Returns true when string matches regex pattern – $matches contains matching strings
-notmatch Returns true when string does not match regex pattern – $matches contains matching strings

Replacement

Operators  Description
-replace replace a string pattern

Type comparison

Operators  Description
-is Returns true if both object are the same type
-isnot Returns true if the objects are not the same type

By default, all comparison operators in powershell’s are case-insensitive. If we need to make a comparison operator case-sensitive, precede the operator name with a “c”. For example, the case-sensitive version of -eq is -ceq. If we need to the case-insensitivity explicit, precede the operator with an i. For example, the explicitly case-insensitive version of -eq is -ieq. Let we discuss more about the each set of operators in upcoming articles.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.