PowerShell 中的逻辑操作符

  1. PowerShell 逻辑运算符
  2. PowerShell 中的 -and 运算符
  3. PowerShell 中的 -or 运算符
  4. PowerShell 中的 -xor 运算符
  5. PowerShell 中的 -not 运算符
PowerShell 中的逻辑操作符

逻辑运算符可以将各种条件转换为单个条件。

本文将讨论现实世界的例子,并在 PowerShell 脚本中应用逻辑运算符。

PowerShell 逻辑运算符

逻辑运算符有 andorxornot!

PowerShell 中的 -and 运算符

如果 $a$btrue,则输出为 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 Paul Kenneth Mendoza avatar Marion Paul Kenneth Mendoza avatar

Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.

LinkedIn