当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] PowerShell - 逻辑运算符 [5 个运算符]

作者:精品下载站 日期:2024-12-14 05:25:31 浏览:16 分类:玩电脑

PowerShell - 逻辑运算符 [5 个运算符]


[玩转系统] PowerShell - 逻辑运算符 [5 个运算符]

在 PowerShell 中使用逻辑运算符

PowerShell 的逻辑运算符是一种强大的工具,用于比较数据并根据这些比较执行操作。它允许用户设计一个比较多个参数的if-then场景。换句话说,它使用户能够按照他们指定的标准做出选择。

逻辑运算符是一个 PowerShell cmdlet,它对两个或多个值执行布尔运算以生成复杂的条件语句。最常用的逻辑运算符是:

  • 逻辑与。
  • 逻辑或。
  • 逻辑异或。
  • 逻辑非。

这些运算符将根据运算结果返回 TrueFalse 值。

使用逻辑 AND 运算符

要对两个或多个值执行逻辑 AND 运算,请在操作数之间使用 -and 运算符。

使用逻辑与运算符:

$operand1 = (1 -eq 2)
$operand2 = ('ab' -eq 'ab')
$operand1 -and $operand2

输出 :

False

在 PowerShell 中,-eq 运算符是比较运算符,用于检查两个值是否相等。如果值相等,则返回 True;否则,返回False。我们使用 -eq 运算符创建两个操作数:

  • operand1 具有 False 值,因为比较数字 12 会产生 False
  • operand2 的值为 True,因为字符串 abab 的比较返回 True.

-and 运算符执行逻辑 AND 运算。如果两个操作数都为 True,则返回 True;否则,False。例如,我们使用 -and 运算符来比较 operand1operand2,结果返回 False,因为 operand1 为 False。

使用逻辑或运算符

要对两个或多个值执行逻辑或运算,请在操作数之间使用 -or 运算符。

使用逻辑或运算符:

$operand1 = (1 -eq 2)
$operand2 = ('ab' -eq 'ab')
$operand1 -or $operand2

输出 :

True

我们像使用 -and 运算符一样创建操作数。此外,我们在本节中使用了 -or 运算符。它执行逻辑“或”运算,如果任一操作数为 True,则返回 True;否则,False

例如,我们使用-or运算符来比较operand1operand2。它返回 True,因为 operand2True

使用逻辑异或运算符

要对两个或多个值执行逻辑异或运算,请在操作数之间使用 -xor 运算符。

使用逻辑异或运算符:

$operand1 = (1 -eq 2)
$operand2 = ('ab' -eq 'ab')
$operand1 -xor $operand2

输出 :

True

-xor 运算符执行逻辑 EXCLUSIVE OR 运算,如果恰好有一个表达式为 True,则返回 True;否则,False。例如,我们对 operand1operand2 使用 -xor 运算,返回 True 因为恰好是 1,即操作数2,为真。

使用逻辑非运算符

要对值执行逻辑 NOT 运算,请在操作数之间使用 -not 或 (!) 运算符。

使用逻辑非运算符:

$operand1 = (1 -eq 2)
$operand2 = ('ab' -eq 'ab')
-not ($operand1)
! ($operand2)

输出 :

True
False

-not 运算符对表达式的值取反。如果表达式为True,则返回False,如果表达式为False,则返回True。我们使用 -not 运算符对两个操作数的值取反。

  • operand1 的否定返回 True,因为表达式为 False
  • operand2 的否定返回 False,因为表达式为 True

使用多个逻辑运算符

要对一个值执行多个逻辑运算,请使用有助于识别的括号。

使用多个逻辑运算符:

$operand1 = (1 -eq 2)
$operand2 = ('ab' -eq 'ab')
(-not($operand1) -and $operand2) -xor $operand2

输出 :

False

请记住,运算符 -and-or-xor 优先于 -not。使用括号来指示运算顺序。我们使用了多个逻辑运算符:

  • operand1 使用否定,结果为 True,因为其表达式为 False
  • operand2operand1 的否定进行逻辑 AND 运算,产生结果 True,因为两个操作数的值都是 确实如此。
  • operand2 和上述 AND 运算的结果应用逻辑异或运算。鉴于两个操作数的值为 True,则返回 False

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯