Logical Operators


PowerShell logical operators are used to test or validate an expression. Typically the result of these operations is TRUE or FALSE. Table 6.2 describes the operators:

image from book
Table 6.2: PowerShell Logical Operators
Open table as spreadsheet

Operator

Description

Example

-and

All expressions must evaluate as TRUE.

(1 -eq 1) -and (2 - eq 2) returns TRUE

-or

At least one expression must evaluate as TRUE.

(1 -eq 1) -or (2 -eq 4) returns TRUE

-not

Evaluates the inverse of one of the expressions.

(1 -eq 1) -and -not (2 -gt 2) returns TRUE

!

The same as -not.

(1 -eq 1) -and ! (2 -gt 2) returns TRUE

image from book

Logical operators should be used when you want to evaluate multiple conditions. While you can evaluate several expressions, your scripts and code will be easier to debug or troubleshoot if you limit the operation to two expressions:

 PS C:\> $varA=5 PS C:\> $varB=5 PS C:\> if (($varA -eq $varB) -and ($varB -gt 20)) >>{ >>Write-Host "Both conditions are true." >>} >>else >>{ >>Write-Host "One or both conditions are false." >>} >> One or both conditions are false. PS C:\> 

Here's the same example using -or:

 PS C:\> if (($varA -eq $varB) -or ($varB -gt 20)) >> { >> Write-Host "At least one condition is true." >> } >> else >> { >> Write-Host "Both conditions are false." >> } At least one condition is true. PS C:\> 

We get a different result if we change $varA to 20:

 PS C:\> $varA=20 PS C:\> if (($varA -eq $varB) -or ($varB -gt 20)) >> { >> Write-Host "At least one condition is true." >> } >> else >> { >> Write-Host "Both conditions are false." >> } >> Both conditions are false. PS C:\> 



Windows PowerShell. TFM
Internet Forensics
ISBN: 982131445
EAN: 2147483647
Year: 2004
Pages: 289

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net