如何使用PowerShell的If语句为脚本添加条件逻辑

PowerShell 是一种强大的脚本语言,有许多原因支持它。其中一个原因是它支持条件逻辑,可以帮助您加强您的 PowerShell 脚本,使其更加高效和有效。在本文中,我将教您如何使用IfElseElseif条件逻辑,并解释这如何帮助您作为 PowerShell 脚本编写者。

如何使用 PowerShell If 语句

PowerShell If 语句用于执行代码的条件执行。它们允许您测试条件并根据条件评估为真或假来执行不同的代码块。

让我们从两个示例开始,展示如何使用 PowerShell If语句。

示例 1:检查一个数字是正数还是负数

在下面的示例中,我们有一个变量 $number,设置为 10。If语句使用 -gt 运算符检查 $number 的值是否大于 0。

  • 当条件为真时,它执行第一组花括号内的代码块,这种情况下打印“这个数字是正数”。
  • 当条件为假时,它转到Elseif块,并检查数字是否小于 0,使用 -lt 运算符。
  • 如果条件为真,则执行第二组花括号中的代码,打印“数字为负数”。
  • 如果两个条件都为假,则执行else块中的代码,打印“数字为零。”
$number = 10

if ($number -gt 0) {
    Write-Host “The number is positive.”
} elseif ($number -lt 0) {
    Write-Host “The number is negative.”
} else {
    Write-Host “The number is zero.”
}
Checking if a number is positive or negative (Image credit: Petri/Bill Kindle)

示例2:检查文件是否存在

在下一个示例中,我们有一个变量$file,设置为文件的路径。If语句使用Test-Path cmdlet来检查文件是否存在。

  • 如果条件评估为真,表示文件存在,则执行第一组花括号中的代码,打印“文件存在”。
  • 如果条件为假,则执行else块中的代码,打印“文件不存在。”
$file = “C:\path\to\file.txt”

if (Test-Path $file) {
    Write-Host “The file exists.”
} else {
    Write-Host “The file does not exist.”
}
Checking if a file exists (Image credit: Petri/Bill Kindle)

这只是 PowerShell 中条件语句如何工作的两个基本示例。让我们继续学习Else语句。

如何在 If 语句中使用 PowerShell Else 语句

在PowerShell中,您可以使用Else语句与If语句结合创建条件逻辑。当If语句中的条件为假时,它允许您指定要执行的一段代码。

让我给您举两个示例,展示如何在PowerShell中使用Else语句。

示例3:检查变量是否大于一个数字

在这个示例中,我们进行了几项检查:

  • If语句检查变量$number是否大于10。
  • 如果是,将显示消息“数字大于10”。
  • 如果不符合条件,则运行Else块,并显示消息“数字不大于10”。
$number = 5

if ($number -gt 10) {
    Write-Host “The number is greater than 10.”
}
else {
    Write-Host “The number is not greater than 10.”
}
Checking if a variable is greater than a number (Image credit: Petri/Bill Kindle)

示例4:比较变量的值与字符串

在这个示例中,If语句将变量$user的值与字符串“John”进行比较。

  • 如果它们相等,则显示消息“欢迎,John!”。
  • 如果不符合条件,也就是$user的值不是“John”,则执行Else块,并显示消息“访问被拒绝。您不是John。”。
$user = “John”

if ($user -eq “John”) {
    Write-Host “Welcome, John!”
}
else {
    Write-Host “Access denied. You are not John.”
}
Comparing the value of a variable with a string (Image credit: Petri/Bill Kindle)

如果语句和否则语句的区别在于它们评估的条件以及执行的后续操作。

  • 如果语句检查条件并在条件为真时执行代码。
  • 否则语句提供了一个替代的代码块,用于在如果语句中的条件为假时执行。如果如果语句中的条件为真,则否则块不会运行。

总之,如果语句允许您根据特定条件执行代码。否则语句在条件为假时提供备用选项。通过将这些语句结合在一起,您可以在PowerShell脚本中创建更灵活和健壮的逻辑。

如何使用PowerShell ElseIf语句

ElseIf语句用于创建一个条件,检查前面的如果语句或任何前面的ElseIf语句是否评估为“假”。ElseIf语句允许您测试多个条件,并根据这些条件的评估执行不同的代码块。当您有超过两个结果时,ElseIf语句特别有用。

以下是两个示例,展示了在PowerShell中使用ElseIf语句的用法。

示例5:检查数字范围

在这个例子中,代码检查$number变量的值,并根据其范围执行不同的代码块。

  • 如果数字小于10,则第一个条件为真,并显示相应的消息。
  • 如果不是,则使用ElseIf语句检查下一个条件。当数字在10到19之间(包括10和19)时,第二个条件为真,并显示相应的消息。
  • 如果前面的条件都不为真,则执行Else块,显示一个消息,显示数字为20或更大。
$number = 25

if ($number -lt 10) {
    Write-Host “The number is less than 10.”
}
elseif ($number -ge 10 -and $number -lt 20) {
    Write-Host “The number is between 10 and 19.”
}
else {
    Write-Host “The number is 20 or greater.”
}
Checking a number’s range (Image credit: Petri/Bill Kindle)

示例6:检查字符串的长度

在这个例子中,代码检查$name字符串的长度,并根据其长度确定其类别。

  • 当名称超过10个字符时,第一个条件为真,并显示相应的消息。
  • 当第一个条件为假时,我们使用ElseIf语句检查下一个条件。如果名称超过5个字符(但不超过10个字符),第二个条件为真,并显示相应的消息。
  • 如果前面的条件都不为真,则执行Else块,并显示一个消息,显示名称为5个字符或更短。
$name = “John”

if ($name.Length -gt 10) {
    Write-Host “The name is longer than 10 characters.”
}
elseif ($name.Length -gt 5) {
    Write-Host “The name is between 6 and 10 characters.”
}
else {
    Write-Host “The name is 5 characters or shorter.”
}
Checking a string’s length (Image credit: Petri/Bill Kindle)

总的来说,PowerShell中的ElseIf语句指定在前面的语句评估为假时要检查的条件。它们提供了一种处理多个条件并相应执行不同代码块的方法。

如何在PowerShell中使用AND/OR语句与If语句

在PowerShell中,“AND”和“OR”是逻辑运算符,用于将多个条件组合在条件语句中,以控制脚本的流程。它们可以与If语句一起使用,同时评估多个条件:

让我给您提供两个示例,展示它们的用法并突出与IfElse语句的区别。

示例7:使用AND运算符

假设您想使用PowerShell检查用户是否是管理员,以及他们的帐户是否当前活动。您可以使用AND运算符同时评估这两个条件。

在此示例中,脚本检查$ isAdministrator和$ isAccountActive变量是否都为true。如果两个条件都为true,则脚本会打印一条消息,显示用户是具有活动帐户的管理员。否则,它将打印一条消息,显示用户不是管理员,或者他们的帐户不活动。

$user = “John”
$isAdministrator = $true
$isAccountActive = $false

if ($isAdministrator -and $isAccountActive) {
    Write-Host “$user is an administrator with an active account.”
} else {
    Write-Host “$user is not an administrator, or their account is inactive.”
}
Checking if a user is an administrator and if their account is currently active (Image credit: Petri/Bill Kindle)

示例8:使用“OR”运算符

假设您想要检查服务器是否运行Windows Server 2016Windows Server 2019。使用PowerShell,您可以使用OR运算符来评估这些条件。

在这个示例中,脚本使用OR运算符来检查$osVersion变量是否等于“Windows Server 2016”或“Windows Server 2019”。如果条件评估为真,则打印一条消息,显示服务器正在运行受支持的操作系统。否则,它会打印一条消息,显示服务器正在运行不受支持的操作系统。

$server = “Server01”
$osVersion = “Windows Server 2012”

if ($osVersion -eq “Windows Server 2016” -or $osVersion -eq “Windows Server 2019”) {
    Write-Host “$server is running a supported operating system.”
} else {
    Write-Host “$server is running an unsupported operating system.”
}
Checking if our variable is equal to either Windows Server 2016 or Windows Server 2019 (Image credit: Petri/Bill Kindle)

示例9:与IfElse语句比较

ANDOR运算符提供了一种简洁的方法来同时评估多个条件。它们与IfElse语句不同,后者一次只评估一个条件。如果IfElse语句中的条件为真,则执行与If语句关联的代码块。否则,执行与Else语句关联的代码块。

为了展示这一点,让我们将示例1更改为使用一个IfElse语句。在这个改变后的示例中,脚本首先检查用户是否是管理员。如果为真,则检查账户是否激活。根据每个条件的评估,它执行不同的代码块。

$user = “John”
$isAdministrator = $true
$isAccountActive = $false

if ($isAdministrator) {
    if ($isAccountActive) {
        Write-Host “$user is an administrator with an active account.”
    } else {
        Write-Host “$user is an administrator, but their account is inactive.”
    }
} else {
    Write-Host “$user is not an administrator.”
}
Comparison with IfElse statements (Image credit: Petri/Bill Kindle)

使用这种方法可以对脚本的流程进行细粒度控制。然而,与使用逻辑运算符如“AND”和“OR”相比,它可能导致嵌套代码块和增加的复杂性。

如何在If语句中使用PowerShell here-strings

在PowerShell中,here-strings用于创建多行字符串文字。当处理大块文本或需要保留格式时,它们非常有用。

当在If语句中使用here-strings时,可以将一个字符串值与多行字符串进行比较。以下是在PowerShell If语句中使用here-strings的语法:

if ($string -eq @’
    Multi-line
    string
    ‘@)
{
    # Code to execute if the condition is true
}
else
{
    # Code to execute if the condition is false
}

让我给你两个示例,以帮助你更好地理解如何在If语句中使用here-strings。

示例10:检查特定消息

假设我们有一个 PowerShell 脚本,提示用户输入,并且我们想要检查用户是否输入了特定消息,比如“Hello, world!”。我们可以在一个 here-string 内部的 if 语句中,将用户输入与预期消息进行比较。

在以下示例中,脚本提示用户输入消息,并将输入存储在 $userInput 变量中。然后,if 语句使用 here-string 将用户输入与预期消息进行比较。如果输入与预期消息匹配,则显示“用户输入了正确的消息”消息;否则,显示“用户输入了不同的消息”。

$userInput = Read-Host “Enter a message”

if ($userInput -eq @’
Hello, world!
‘@)
{
    Write-Host “User entered the correct message.”
}
else
{
    Write-Host “User entered a different message.”
}
Using here-strings to check for a specific message (Image credit: Petri/Bill Kindle)

示例 11:比较脚本块

这里是另一个示例,我们想要比较一个脚本块和一个预定义的代码块。我们可以使用 here-strings 来定义脚本块,然后在一个 If 语句中进行比较。

在这个示例中,我们有两个脚本块,$predefinedCode 和 $userCode。我们想要检查用户代码是否与预定义代码匹配。通过使用 here-strings 来定义脚本块,我们可以在 If 语句中进行比较。

如果用户代码与预定义代码匹配,则显示“用户代码与预定义代码匹配”消息;否则,显示“用户代码与预定义代码不同”。

$predefinedCode = {
    Write-Host “This is some code.”
    Write-Host “It does something.”
}

$userCode = {
    Write-Host “This is some code.”
    Write-Host “It does something.”
}

if ($userCode -eq $predefinedCode)
{
    Write-Host “The user code matches the predefined code.”
}
else
{
    Write-Host “The user code differs from the predefined code.”
}
Using here-strings to compare a script block (Image credit: Petri/Bill Kindle)

如何在 If 语句中使用连接

在PowerShell中,您可以使用’+’算术运算符来连接字符串。要在If语句中使用连接,您需要通过组合多个字符串变量或文字来构建一个新的字符串。

以下是两个示例,用于说明PowerShellIf语句中连接的用法:

示例12:连接字符串变量

在这个示例中,定义了两个字符串变量,$firstName和$lastName。If语句检查这两个变量是否有值(即它们不是空字符串)。

  • 如果两个条件都为真,我们使用+运算符连接名字和姓氏,并将结果存储在$fullName变量中。然后,我们使用Write-Host命令显示连接的全名。
  • 如果名字的第一个或最后一个部分缺失,我们将看到else块运行并显示适当的消息。
$firstName = “John”
$lastName = “Doe”

if ($firstName -ne ” -and $lastName -ne ”) {
    $fullName = $firstName + “ “ + $lastName
    Write-Host “Full Name: $fullName”
} else {
    Write-Host “First name or last name is missing.”
}
Concatenating string variables (Image credit: Petri/Bill Kindle)

示例13:连接字符串文字

在这个第二个示例中,定义了三个变量:$greeting的值为“你好”,$name的值为“Alice”,$age的值为30。if语句使用IsNullorEmpty()方法检查$name变量是否有值。

  • 如果为真,我们创建一个消息,该消息使用+运算符连接问候语、姓名和年龄。我们将结果消息存储在$message变量中,然后使用Write-Host命令显示它。
  • 如果名字缺失(空字符串),则else块运行并显示适当的错误消息。
$greeting = “Hello”
$name = “Alice”
$age = 30

if ([string]::IsNullorEmpty($name) -eq $false){
    $message = $greeting + “, “ + $name + “! Your age is “ + $age + “.”
    Write-Host $message
} else {
    Write-Host “Name is missing.”
}
Concatenating string literals (Image credit: Petri/Bill Kindle)

总的来说,这两个示例展示了如何根据特定条件动态地组合字符串的连接操作。

如何在If语句中使用连接字符串

连接字符串通常用于建立到数据库或其他外部系统的连接。这些字符串包含有关服务器、数据库名称、凭据和建立连接所需的其他参数的信息。

If语句中,您可以使用连接字符串来根据连接的成功或失败运行特定的代码块。以下是两个示例,展示了在PowerShell If语句中使用连接字符串的用法:

示例 14:检查数据库连接

在这个示例中,我们定义了一个连接字符串($connectionString),指定了服务器名称、数据库名称和凭据。然后我们使用连接字符串创建一个SqlConnection对象。在try块中,我们尝试使用$connection.Open()打开连接。

  • 如果连接成功,代码块将在try块下执行,显示一个成功的连接。
  • 如果发生异常(即连接失败),代码块将在catch块下执行,显示一个失败的连接。
# Define the connection string
$connectionString = “Server=server_name;Database=db_name;User Id=user_id;Password=password;"

# Create a SqlConnection object using the connection string
$connection = New-Object System.Data.SqlClient.SqlConnection($connectionString)

# Attempt to establish the connection
try {
    $connection.Open()
   
    # Connection successful
    Write-Host “Connected to the database.”

    # Perform additional operations on the database if needed

    # Close the connection
    $connection.Close()
}
catch {
    # Connection failed
    Write-Host “Failed to connect to the database.”
}
Checking a database connection (Image credit: Petri/Bill Kindle)

示例 15:检查网络连接

在第二个示例中,我们定义了一个连接字符串($connectionString),指定了服务器名称和端口号。然后我们使用连接字符串创建一个TcpClient对象。在try块中,我们尝试使用$tcpClient.Connect(”server_name”, 1234)建立与服务器的连接。

  • 如果连接成功,代码块将在try块下执行,显示一个成功的连接。
  • 如果发生异常(即连接失败),则在catch块下执行代码块,显示连接失败。
# Define the connection string
$connectionString = “Server=server_name;Port=1234;"

# Create a TcpClient object using the connection string
$tcpClient = New-Object System.Net.Sockets.TcpClient

# Attempt to establish the connection
try {
    $tcpClient.Connect(”server_name”, 1234)
   
    # Connection successful
    Write-Host “Connected to the server.”

    # Perform additional operations if needed

    # Close the connection
    $tcpClient.Close()
}
catch {
    # Connection failed
    Write-Host “Failed to connect to the server.”
}
Checking a network connection (Image credit: Petri/Bill Kindle)

上述示例是简化的,假设没有抛出异常则连接成功。在实际场景中,适当处理异常非常重要。您应根据连接的具体要求使用额外的错误处理和身份验证机制。

如何在If语句中使用Break和Continue语句

在PowerShell中,BreakContinue语句用于控制循环和开关内的执行流程。虽然Break允许您退出循环或开关,Continue则让您跳过当前迭代并转到下一个迭代。

尽管这些语句通常用于循环内,您也可以在If语句内部使用它们以实现特定行为。让我们通过两个易于理解的示例探讨如何在If语句中使用BreakContinue

示例16:在If语句中使用Break

在这个示例中,我们有一个从1到10的数字数组。我们使用一个Foreach循环来遍历每个数字。在循环中,我们检查当前数字是否等于6。

  • 如果是,我们显示一条消息,然后使用break语句退出循环。
  • 如果数字不等于6,我们简单地显示当前数字。
  • 当循环遇到数字6时,它会跳出循环,程序继续执行后续代码。
$numbers = 1..10

foreach ($number in $numbers) {
    if ($number -eq 6) {
        Write-Host “Found the number 6. Exiting the loop.”
        break
    }
   
    Write-Host “Current number is: $number”
}
Using Break in an If statement (Image credit: Petri/Bill Kindle)

示例17:在If语句中使用Continue

在这个示例中,我们再次有一个从1到10的数字数组。我们使用一个Foreach循环来遍历每个数字。首先,我们检查当前数字是否为3或7。

  • 如果为真;我们显示一条消息,然后使用Continue语句跳过当前迭代,进入下一个迭代。
  • 如果数字不是3或7,我们显示当前数字。循环将继续,直到我们评估所有数字。
$numbers = 1..10

foreach ($number in $numbers) {
    if ($number -eq 3 -or $number -eq 7) {
        Write-Host “Skipping the number $number”
        continue
    }
   
    Write-Host “Current number is: $number”
}
Using Continue in an If statement (Image credit: Petri/Bill Kindle)

在这两个示例中,我们使用If语句根据特定条件有条件地运行某些操作。Break语句允许我们退出循环或完全切换,而Continue语句跳过当前迭代中的剩余代码,进入下一个迭代。

如何在If语句中使用hashtables

在PowerShell中,您可以在hashtables中使用If语句,根据键值对执行条件检查。Hashtables是一组键值对的集合,其中每个键都是唯一的。

以下是两个示例,展示如何在PowerShell的If语句中使用hashtables。

示例18:检查hashtable中是否存在特定键

在此示例中,我们有一个名为$myHashtable的hashtable,其中包含三个键值对。If语句使用ContainsKey()方法检查hashtable中是否存在键“Age”。如果键存在,则打印一条消息,说明年龄存在;否则,打印一条消息,说明年龄不存在。

# Create a hashtable
$myHashtable = @{
    “Name” = “John”
    “Age” = 30
    “City” = “New York”
}

# Check if a specific key exists in the hashtable
if ($myHashtable.ContainsKey(”Age”)) {
    Write-Host “Age is present in the hashtable.”
}
else {
    Write-Host “Age is not present in the hashtable.”
}
Checking if a specific key exists in a hashtable (Image credit: Petri/Bill Kindle)

示例19:检查hashtable中是否存在特定值

在此示例中,我们再次使用相同的名为$myHashtable的hashtable。If语句使用ContainsValue()方法检查hashtable中是否存在值“New York”。如果值存在,则打印一条消息,说明城市是纽约;否则,打印一条消息,说明城市不是纽约。

# Create a hashtable
$myHashtable = @{
    “Name” = “John”
    “Age” = 30
    “City” = “New York”
}

# Check if a specific value exists in the hashtable
if ($myHashtable.ContainsValue(”New York”)) {
    Write-Host “The city is New York.”
}
else {
    Write-Host “The city is not New York.”
}
Checking if a specific value exists in a hashtable (Image credit: Petri/Bill Kindle)

如何在If语句中使用数组

在PowerShell中,我们可以在If语句中使用数组来检查特定条件,并根据这些条件执行特定操作。以下是两个示例,展示了在If语句中使用数组的用法。

示例20:检查数组是否包含特定值

在这个示例中,我们有一个名为$numbers的数组,其中包含一系列数字。If语句使用-contains运算符检查数组是否包含值’3’。如果条件为真,它将输出“数组包含值3”。否则,它将输出“数组不包含值3”。

# Define an array of numbers
$numbers = 1, 2, 3, 4, 5

# Check if the array contains a specific value, e.g., 3
if ($numbers -contains 3) {
    Write-Host “The array contains the value 3.”
} else {
    Write-Host “The array does not contain the value 3.”
}
Checking if an array contains a specific value (Image credit: Petri/Bill Kindle)

示例21:检查数组是否为空

在这个示例中,我们有一个名为$emptyArray的空数组。If语句检查数组的长度属性是否等于0。如果条件为真,它将输出“数组为空”。否则,它将输出“数组不为空”。

# Define an empty array
$emptyArray = @()

# Check if the array is empty
if ($emptyArray.Length -eq 0) {
    Write-Host “The array is empty.”
} else {
    Write-Host “The array is not empty.”
}
Checking if an array is empty (Image credit: Petri/Bill Kindle)

如何在PowerShell中使用Switch语句

在PowerShell中,Switch语句提供了一种根据变量或表达式的值执行条件分支的方式。它允许您将单个值与多个值进行比较,并根据匹配情况执行不同的代码块。

以下是如何在PowerShell中使用Switch语句的解释,附有两个易于理解的示例。

示例22:检查一周中的日期

在这个示例中,我们有一个$day变量,它将是当前日期。Switch语句使用字符串“Monday”、“Tuesday”等检查$day的值是否匹配不同的情况。

  • 如果匹配成功,脚本将执行相应的代码块。
  • 如果没有匹配成功,脚本将执行默认块。在这里,输出将是“这是一周的开始!”
$day = (Get-Date).DayOfWeek

switch ($day) {
    “Monday” {
        Write-Host “It’s the start of the week!”
    }
    “Tuesday” {
        Write-Host “It’s Tuesday!”
    }
    “Wednesday” {
        Write-Host “It’s the middle of the week!”
    }
    “Thursday” {
        Write-Host “It’s almost Friday!”
    }
    “Friday” {
        Write-Host “It’s finally Friday!”
    }
    Default {
        Write-Host “It’s the weekend!”
    }
}
Using a Switch statement to check for days of the week (Image credit: Petri/Bill Kindle)

示例23:对数字进行分类

在第二个示例中,我们有一个值为42的$number变量。Switch语句使用脚本块检查$number的值是否匹配不同的情况。第一个情况检查数字是否小于0,第二个情况检查数字是否大于0,如果没有其他情况匹配,则运行默认块。在这里,输出将是“正数”。

$number = 42

switch ($number) {
    { $_ -lt 0 } {
        Write-Host “Negative number”
    }
    { $_ -gt 0 } {
        Write-Host “Positive number”
    }
    Default {
        Write-Host “Zero”
    }
}
Using a Switch statement to categorize numbers (Image credit: Petri/Bill Kindle)

在这两个示例中,您可以自定义每种情况中的代码块,以执行基于匹配条件的任何所需操作。 Switch 语句是 PowerShell 中的一个强大结构,提供了一种优雅的方式来处理多个条件以运行代码块。

PowerShell 和条件逻辑:摘要

总的来说,If 语句及其相关结构为在 PowerShell 脚本中实现条件逻辑提供了强大的工具。If 语句对于执行代码的条件执行至关重要,因为它们允许您测试条件并根据条件评估为真或假来执行不同的代码块。

我在本文中提供的示例演示了如何使用 PowerShell If 语句来检查数字是正数还是负数,或者文件是否存在。然而,我在本文中详细介绍了许多其他条件逻辑技巧,以帮助您成为更好的 PowerShell 脚本编写者。这里的信息非常密集,所以这是您需要记住的内容。

  • Else 语句与 If 语句结合使用,创建条件逻辑,提供了当条件不满足时的备用选项。
  • ElseIf 语句也可以用于创建仅在前面的 IfElseIf 语句评估为假时才检查的条件,从而实现更复杂的条件逻辑。
  • 逻辑运算符如AND和OR可用于组合多个条件在If语句中控制脚本流程。Here-strings也可在If语句中用于比较字符串值与多行字符串。
  • 使用‘+’运算符连接字符串还允许您根据特定条件动态组合字符串在If语句中。
  • 连接字符串通常在If语句中用于根据连接到数据库或外部系统的成功或失败有条件地执行代码块。
  • Break和Continue语句提供对循环和开关执行的控制,并可在If语句中使用它们以实现特定行为。
  • Hashtables和数组也可在If语句中用于检查特定条件并根据这些条件执行操作。
  • 最后,Switch语句允许根据变量或表达式的值进行条件分支,从而根据匹配执行不同的代码块。

感谢阅读关于PowerShell If语句的详细指南,如有任何问题,请在下方评论区提问!

Source:
https://petri.com/powershell-if-statement/