The logical operators are used to combine
expressions, allowing you to check multiple conditions in one
statement. Expressions on the left and the right side of any of these
operators are evaluated (if necessary), converted to Boolean values of True or False, and then the combination of those values is returned, following the rules of formal logic. Table 1 lists the logical operators supported by Windows PowerShell.
Table 1. Windows PowerShell Logical Operators
Operator | Description |
---|
-and | Returns True when both left and right hand side expressions evaluate to true |
-or | Returns True when an expression on at least one side evaluates to true |
-xor | Returns True when left and right side expressions have opposite values (one is True and the other is False) |
-not | Changes the Boolean value of the expression that follows it for the opposite |
! | Same as -not |
With the -and operator, you can evaluate multiple expressions. If all the expressions evaluate to true, the Boolean value of True is returned.
PS > (1 -eq 1) -and (2 -eq 2)
True
PS > (1 -eq 1) -and (2 -eq 3)
False
The first example returns True, since both expressions evaluate to True. The second example returns False, since the last expression does not evaluate to true.
The –or operator returns True if one or more expressions evaluate to true.
PS > (1 -eq 1) -or (2 -eq 2)
True
PS > (1 -eq 1) -or (2 -eq 3)
True
The -xor operator returns True only if one of the expressions evaluates to true.
PS > (1 -eq 1) -xor (2 -eq 2)
False
PS > (1 -eq 1) -xor (2 -eq 3)
True
The -not operator returns True if the right value evaluates to false.
PS > -not (1 -eq 1)
False
PS > -not (1 -eq 2)
True
PS > !(1 -eq 2)
True