Edit

Share via


about_Logical_Operators

Short description

Describes the operators that connect statements in PowerShell.

Long description

The PowerShell logical operators connect expressions and statements, allowing you to use a single expression to test for multiple conditions.

Statements that use the logical operators return boolean (TRUE or FALSE) values.

The PowerShell logical operators evaluate only the statements required to determine the truth value of the statement. If the left operand in a statement that contains the -and operator is FALSE, the right operand isn't evaluated. If the left operand in a statement that contains the -or statement is TRUE, the right operand isn't evaluated. As a result, you can use these statements in the same way that you would use the if statement.

Important

The -and, -or and -xor operators have equal precedence. They are evaluated from left to right as they appear within the expression. For more information, see about_Operator_Precedence.

Syntax

The syntax of the logical operators is as follows:

<statement> {-and | -or | -xor} <statement>
{! | -not} <statement>

Examples

The following example uses the -and and -or operators to connect three conditional statements. The result is TRUE only when the value of $a is greater than the value of $b, and either $a or $b is less than 20.

($a -gt $b) -and (($a -lt 20) -or ($b -lt 20))

PowerShell supports the following logical operators.

  • Logical AND (-and) - TRUE when both statements are TRUE.

    (1 -eq 1) -and (1 -eq 2)   # Result is False
    
  • Logical OR (-or) - TRUE when either statement is TRUE.

    (1 -eq 1) -or (1 -eq 2)    # Result is True
    
  • Logical EXCLUSIVE OR (-xor) - TRUE when only one statement is TRUE

    (1 -eq 1) -xor (2 -eq 2)   # Result is False
    
  • Logical NOT (-not) or (!) - Negates the statement that follows.

    -not (1 -eq 1)             # Result is False
    !(1 -eq 1)                 # Result is False
    

The previous examples also use the equality comparison operator, -eq. For more information, see about_Comparison_Operators. The examples also use the boolean values of integers. The integer 0 has a boolean value of FALSE. All other integers have a value of TRUE.

See also