PowerShell 中的邏輯運算符
- PowerShell 邏輯運算符
-
PowerShell 中的
-and運算符 -
PowerShell 中的
-or運算符 -
PowerShell 中的
-xor運算符 -
PowerShell 中的
-not運算符
邏輯運算符可以將各種條件轉換為單一條件。
本文將討論現實世界的例子並在 PowerShell 中應用邏輯運算符。
PowerShell 邏輯運算符
邏輯運算符包括 and、or、xor 和 not 或 !。
PowerShell 中的 -and 運算符
如果 $a 和 $b 都為 true,則輸出為 true;否則為 false。
真值表:
| A | B | 輸出 |
|---|---|---|
| 0 | 0 | 0 |
| 1 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 1 | 1 |
$a = 0
$b = 0
$a -and $b # false (if both variables are false)
$a = 1
$b = 0
$a -and $b # false (if any of the variables are false)
$a = 1
$b = 1
$a -and $b # true (if both variables are true)
-and 運算符僅在兩者都為 true 時返回 true。一般而言,-and 運算符用於需要檢查並滿足所有條件的情況。
以下是必須滿足的兩個條件的例子。
$attendance = 102
$paid = "Y"
if ($attendance -gt 100 -and $paid -eq "Y") {
Write-Output "Allow for examination."
}
輸出:
Allow for examination.
PowerShell 中的 -or 運算符
如果 $a 和 $b 為 false,則輸出為 false,這與 -and 運算符相比。
-or 運算符只需要一個變量為 true 即可輸出 true。
真值表:
| A | B | 輸出 |
|---|---|---|
| 0 | 0 | 0 |
| 1 | 0 | 1 |
| 0 | 1 | 1 |
| 1 | 1 | 1 |
$a = 0
$b = 0
$a -or $b # false (if both conditions are false)
$a = 1
$b = 0
$a -or $b # true (if any of the variables are true)
$a = 1
$b = 1
$a -or $b # true (if both of the variables are true)
-or 運算符僅在兩個條件都為 false 時返回 false。一般而言,-or 運算符在考慮任何條件為 true 時使用。
$attendance = 99
$marks = 201
if ($attendance -gt 100 -or $marks -gt 200) {
Write-Output "Give five extra marks."
}
輸出:
Give five extra marks.
PowerShell 中的 -xor 運算符
只有當 $a 或 $b 中只有一個為 true 時,獨佔的 or 或 -xor 結果為 true。如果兩個條件都為 true,則 -xor 產生的結果為 false。
真值表:
| A | B | 輸出 |
|---|---|---|
| 0 | 0 | 0 |
| 1 | 0 | 1 |
| 0 | 1 | 1 |
| 1 | 1 | 0 |
('a' -eq 'A') -xor ('a' -eq 'z') # true as one of them is true
('a' -eq 'A') -xor ('Z' -eq 'z') # false as both of them is true
('a' -eq 's') -xor ('Z' -eq 'p') # false as both of them are false
PowerShell 中的 -not 運算符
-not 運算符返回表達式輸出的相反。如果表達式的輸出為 true,則運算符將其返回為 false,反之亦然。
-not ('a' -eq 'a') # false as the output of expression is true
-not ('v' -eq 'a') # true as output expression is false
-not ('v' -eq 'V') # false as output expression is true
-not ('V' -eq 'V1') # true as output expression is false
感嘆號 ! 與 -not 運算符相同。
!('a' -eq 'a') # false as the output of expression is true
!('v' -eq 'a') # true as output expression is false
!('v' -eq 'V') # false as output expression is true
!('V' -eq 'V1') # true as output expression is false
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.
LinkedIn