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

[玩转系统] PowerShell 不是运算符 [带有示例]

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

PowerShell 不是运算符 [带有示例]


您想了解 PowerShell 中的 not 运算符吗?在本教程中,我将解释有关 PowerShell Not 运算符的所有内容、其语法以及 PowerShell 中 not 运算符的一些示例。

PowerShell 中的 Not 运算符是什么?

PowerShell 中的 Not 运算符用于反转其操作数的逻辑状态。换句话说,它将 True 更改为 False,并将 False 更改为 True。该运算符在 PowerShell 中由 -not 表示,但它还有一个可以互换使用的别名 !。 PowerShell 中的 Not 运算符用于反转表达式的布尔值。

句法

Not 运算符在 PowerShell 中可以以两种形式使用:

  • -not:标准形式。
  • !:别名,更加简洁,为了简洁起见经常在脚本中使用。

PowerShell 中 Not 运算符的语法为:

-not <expression>

或者

!<expression>

PowerShell 非运算符示例

现在,让我向您展示如何在 PowerShell 中使用 -not 运算符的几个示例。

1. 基本示例

让我们看一下如何在 PowerShell 中使用 Not 运算符的基本示例:

$trueValue = $true
$falseValue = -not $trueValue
Write-Output $falseValue

在此示例中,$trueValue 设置为 True。通过应用 -not 运算符,$falseValue 变为 False

我使用 VS code 执行了上述脚本,您可以在下面的屏幕截图中看到输出:

[玩转系统] PowerShell 不是运算符 [带有示例]

2. 在条件语句中使用 not

Not 运算符经常在 PowerShell if 语句中使用,根据条件的否定来执行代码。

这是一个例子。

$number = 10

if (-not ($number -eq 5)) {
    Write-Output "The number is not 5"
}

此处,条件检查 $number 是否不等于 5。由于 $number 为 10,因此输出将为“The number is not 5”。

我执行了上面的 PowerShell 脚本,您可以在下面的屏幕截图中看到输出:

[玩转系统] PowerShell 不是运算符 [带有示例]

3.与其他逻辑运算符结合

Not 运算符可以与其他逻辑运算符组合以在 PowerShell 中形成更复杂的条件。

这是一个例子。

$isRaining = $false
$isWeekend = $true

if (-not $isRaining -and $isWeekend) {
    Write-Output "You can go for a walk"
}

在此示例中,仅当不下雨并且是周末时才显示消息“您可以去散步”。

这是另一个例子:

Not 运算符可以与其他逻辑运算符(例如 -and、and -or)组合使用:

$x = 10
$y = 20
if (-not ($x -gt 15 -and $y -lt 25)) {
    Write-Host "At least one condition is false"
}

您可以在下面的屏幕截图中看到输出:

[玩转系统] PowerShell 不是运算符 [带有示例]

这是如何在 PowerShell 的 if 语句中使用 not 运算符的示例。

查看 PowerShell 逻辑运算符

4. 使用 !别名

在 PowerShell 中,!符号可以用作 -not 的替代,但只能在布尔表达式的上下文中使用。

这是一个例子。

$isAdmin = $false
if (!$isAdmin) {
    Write-Host "User is not an admin"
}

5. 检查 Null 或空字符串

Not 运算符对于检查 PowerShell 中的字符串是否为 null 或空特别有用。

这是一个例子。

$string = ""

if (-not [string]::IsNullOrEmpty($string)) {
    Write-Output "The string is not empty"
} else {
    Write-Output "The string is empty"
}

在这种情况下,由于 $string 为空,因此输出将为“The string isempty”。

结论

PowerShell 中的 Not 运算符用于对布尔表达式求反。在本教程中,我解释了如何在 PowerShell 中使用 Not 运算符及其语法,我们还看到了 PowerShell 中 not 运算符的一些示例。

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

取消回复欢迎 发表评论:

关灯