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

[玩转系统] 如何使用 PowerShell If Else 语句

作者:精品下载站 日期:2024-12-14 03:44:19 浏览:14 分类:玩电脑

如何使用 PowerShell If Else 语句


If-Else 语句是任何编程语言的基础,在 PowerShell 中也是如此。它们用于测试是否满足条件,允许您根据结果执行不同的操作。

多个条件、if-not 语句和 else-if 语句为您提供了多种选项来测试每种情况下的条件。充分理解 if 语句和不同的方法确实可以帮助您编写更好的 PowerShell 脚本。

在本文中,我们将了解 PowerShell If Else 语句,使用 if not、if and 等不同方法,以及如何使用多个条件。

PowerShell If 语句

让我们从 PowerShell 中的基本 If 语句开始。不带任何运算符的 If 语句将检查条件是否为真。当条件为真时,将执行脚本块。条件放在括号 ( ) 之间,脚本块放在大括号 { } 之间。

if (condition) {
  # code to execute if condition is true
}

在下面的示例中,我们将变量 $isAdmin 设置为 True。接下来,我们将使用 if 语句检查变量是否设置为 true 并写入输出:

$isAdmin = $true

if ($isAdmin) {
    Write-Host "You have administrator privileges."
} 

在上面的示例中,我们使用了一个简单变量,该变量设置为 $true 作为条件语句。但我们也可以在条件中使用比较运算符。比较运算符根据结果返回 true 或 false。在 PowerShell 窗口中尝试以下操作:

$num = 10 
$num -gt 5

# Result
True

[玩转系统] 如何使用 PowerShell If Else 语句

如您所见,比较运算符返回 true。因此,如果我们将这个示例添加到 If 语句的条件部分中,我们可以测试数字 $num 是否大于 5,并向控制台输出一个字符串:

$num = 10

if ($num -gt 5) {
  # $num is greater then 5
  Write-Host "$num is greater then 5"
}

您在 PowerShell 中使用的其他比较运算符有:

OperatorCounter-Part operatorDescription-eq-neEqual or not equal-gt-ltGreater or less than-geGreat than or equal to-leLess than or equal to-Like-NotLikeMatch a string using * wildcard or not-Match-NotMatchMatches or not the specified regular expression-Contains-NotContainsCollection contains a specified value or not-In-NotInSpecified value in collection or not-ReplaceReplace specified value

在 If 条件中使用 Cmdlet

除了变量和比较运算符之外,我们还可以在 if 语句条件中使用 cmdlet。例如,仅当对服务器的 ping 操作成功时,我们才可以使用 test-connection cmdlet 创建与 Server01 的 PowerShell 会话。

if (Test-Connection -TargetName Server01 -Quiet) { 
  New-PSSession -ComputerName Server01 
}else{
  Write-Host "Unable to connect to server01"
}

建议

想要了解有关编写 PowerShell 脚本的更多信息,请务必阅读此 PowerShell 脚本编写入门指南

If-Else 语句

在 PowerShell 中,if 语句通常伴随有 else 语句。当条件为 false 或 null 时,执行语句的 else 部分。以最后一个例子为例,我们可以添加一个 else 语句来告诉我们 $num 是否小于 5:

$num = 10

if ($num -gt 5) {
  # $num is greater then 5
  Write-Host "$num is greater then 5"
}else{
  # $num is less then 5
  Write-Host "$num is less then 5"
}

当变量未设置时,if-else 语句的 else 部分也会触发。例如,如果我们将变量 $num 设置为空字符串,则将触发 else 条件:

[玩转系统] 如何使用 PowerShell If Else 语句

If Elseif Else 语句

我们可以使用 elseif 语句进一步扩展 If Else 语句。 Elseif 允许您测试附加条件。值得一提的是,您并不局限于一个 elseif 条件,您可以在 if 和 else 语句之间添加任意数量的条件。但请记住,当满足 if 语句或 elseif 语句之一时,将不再测试其他语句。

$num = 10

if ($num -gt 10) {
  Write-Host "$num is greater then 10"
}elseif ($num -gt 5) {
  Write-Host "$num is greater then 5"
}else{
  Write-Host "$num is less then 5"
}

# Result
10 is greater then 5

多个 elseif 语句的另一个选项是使用 switch 语句或使用集合和 -in 比较运算符。 -in 运算符允许您检查集合是否包含指定的值。例如,我们可以检查水果是否在集合中列出:

$collection = @(
  'apple',
  'banana',
  'kiwi',
  'raspberry'
)

$fruit = 'kiwi'
if ($fruit -in $collection) {
  write-host "$fruit is a approved fruit"
}

# Result
kiwi is a approved fruit

PowerShell If 和语句

PowerShell 中的 If And 语句允许您测试单个 if 内的多个条件。这有时消除了嵌套 If 语句或多个 if-else 语句的需要。 If 和语句检查两个或多个条件是否为真。当所有条件都为真时,将执行脚本块:

# Using the -and operator
if ((condition1) -and (condition2)) {
  # code to execute when condition 1 and condition 2
  # are both true
}

我更喜欢将每个条件放在括号 ( ) 之间,这使得代码更具可读性。但它们并不总是必要的,在上面的示例中,您也可以将它们省略,如下所示:

if ($num -ge 1t -and $num -lt 20) { #code }

让我们从一个简单的例子开始,我们将检查数字是否在 10 到 20 之间。我们首先检查变量 $num 是否大于 10,在第二个条件中检查它是否小于20.

$num = 12

if (($num -gt 10) -and ($num -lt 20)) {
  Write-Host "$num is between 10 and 20"
}

# Tip: you could also use the -in operator to check if the number is withing a range:
if ($num -in 11..19) {
  Write-Host "$num is between 10 and 20"
}

请注意,我们正在测试数字是否在 10 到 20 之间。如果您想包含 10 和 20,请使用 -ge(大于或等于)和 -le 运算符(小于或等于)。

使用 If Or 语句

类似于if和检查多个条件是否满足,我们是否也可以用条件运算符-or来测试其中一个条件是否满足。使用 -or 运算符时,只有其中一个条件必须为真才能执行脚本块。

if ((condition1) -or (condition2)) {
  # code to execute when condition 1 or condition 2 is true
}

例如,我们可以在继续之前检查使用的用户角色是管理员还是开发人员:

$role = "developer"

if (($role -eq 'admin') -or ($role -eq 'developer')) {
  # code to execute
  write-host 'The user is allowed to continue'
}

Powershell 如果没有

PowerShell If 语句检查特定条件是否为真,但有时您只想检查条件是否为假。为此,我们可以使用 PowerShell 中的 If Not 语句。这将检查是否不满足条件。 if not 语句的编写方式是将条件放在括号 ( ) 之间,并在其前面放置 !-not

if (!(condition1)) {
  # code to execute when condition 1 is false
}

# or using -not
if (-not(condition1)) {
  # code to execute when condition 1 is false
}

一个很好的例子是 Test-Path cmdlet,它检查路径或文件是否存在。在将文件复制到目录之前,我们需要检查该文件夹是否存在,如果不存在,我们需要创建它。

If (!(Test-Path -Path $pathToFolder -PathType Container)) {
  New-Item -ItemType Directory -Path $pathToFolder | Out-Null
}

PowerShell 三元运算符

如今,一行 if 语句是许多编程语言中的常见做法。一行 if 语句实际上称为三元运算符,我们可以在 PowerShell 7 中使用它。当您有可以在一行上编写的简单短 if 语句时,三元运算符非常有用。当 if 语句触发多行脚本块时,三元运算符不是最佳选择。

三元运算符对 if-else 语句使用以下结构:

<condition> ? <script-when-true> : <script-when-false>;

让我们以文章开头的例子为例。我们将检查该数字是否大于 5。我们可以使用三元运算符将其写在一行上,而不是编写至少 5 行长的完整 if-else 语句:

$value = 10
$value -gt 5 ? (Write-Host 'Greater than 5') : (Write-Host 'Less than or equal to 5')

PowerShell 如果为空

另一种常见做法是检查 cmdlet 的变量或结果是否为 null。空变量是尚未分配值或已显式分配空值的变量。简单来说,空变量中不存储任何数据。

要检查变量或结果是否为 null 或空,我们将其与 $null 变量进行比较。 $null 变量必须位于左侧,以确保 PowerShell 正确比较该值。

假设我们要检查变量是否为空。如果我们将带有空字符串的变量放在左侧,结果将是该变量不为空

$var = ""

if ($var -eq $null) {
  Write-Host "The variable is null."
}else{
  Write-Host "The variable is not empty."
}

# Result
The variable is not empty.

但是,如果我们首先放置 $null 变量,那么结果将是该变量为空:

$var = ""

if ($null -eq $var) {
  Write-Host "The variable is null."
}else{
  Write-Host "The variable is not empty."
}

# Result
The variable is null.

PowerShell 中出现不同结果的原因有两个:

  • $null 是标量值。当左侧的值是标量时,比较运算符返回布尔值;如果是集合,则比较运算符返回匹配值/空数组。
  • PowerShell 执行从左到右的类型转换。当 $null 转换为其他标量类型时,这会导致不正确的比较。

因此,如果你想检查一个值是否为空,那么你必须将 $null 放在左侧。

在 PowerShell 中检查值是否为 null 不仅仅用于变量。您还可以使用它来检查 cmdlet 是否返回任何数据。例如,我们可以使用以下代码检查是否安装了PowerShell模块:

if ($null -eq (Get-Module -ListAvailable -Name Microsoft.Graph)) {
   Write-host "Microsoft Graph module is not installed"
}

总结

PowerShell If Else 语句是编写脚本的基础。它们允许您比较值并根据结果在脚本中做出决策。使用多个 elseif 条件时,您可能需要考虑使用 PowerShell Switch 语句。这使您可以以更干净、更简单的方式检查多个条件。

我希望这篇文章对您有用,如果您有任何疑问,请在下面发表评论。

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

取消回复欢迎 发表评论:

关灯