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

[玩转系统] PowerShell While 循环:回归基础指南

作者:精品下载站 日期:2024-12-14 13:11:41 浏览:15 分类:玩电脑

PowerShell While 循环:回归基础指南


PowerShell 是一种功能强大的脚本语言,提供许多用于自动化和管理基于 Windows 的系统的功能。最常用的结构之一是 PowerShell while 循环。

如果您在尝试学习 PowerShell 脚本编写时陷入了无限循环,请不要担心。让 PowerShell while 循环引导您实现伟大的逃脱。在本教程中,您将在编写脚本时跳回到 PowerShell 中使用 while 循环的基础知识。

继续阅读,将您的 PowerShell 脚本编写技能提升到新的水平!

先决条件

本教程将是一个实践演示。要继续操作,请确保您具备以下条件:

  • Windows 计算机 - 本教程使用 Windows 10。
  • 安装了 Windows PowerShell 5.0 或更高版本 - 本教程使用 PowerShell 7。
  • 具有管理员权限的用户帐户。

执行单个条件 while 循环

while 循环最简单的类型之一是单一条件类型。与 If 语句不同,只要指定的条件计算结果为 true,这种类型的循环就会执行一组给定的命令。当返回“False”时,循环中断,并继续执行脚本的其余部分。

以下是单个条件 while 循环的语法:

  • 您首先会注意到的是括号的使用。条件必须括在括号内,而代码块是一组在条件为 true 时执行的 PowerShell 命令。
  • 第二件事要注意的是,条件必须返回布尔值,其计算结果为 True 或 False。
while (condition)
{

	# Code block to execute

}

运行下面的代码,其中 $val 的值从 0 开始,每次代码块运行时都会增加 1,直到 >$val 变量的值等于3

$val 达到值 3 时(这使得条件为 False),循环将中断,并继续执行脚本的其余部分。

# Declares the $val variable with the initial value of 0
$val = 0

# Sets the while loop to run until the $val variable's value reaches 3
while($val -ne 3)
{
	# Increments the $val variable's value by 1
	$val++
	
	# Prints the current value of the $val variable
	Write-Host $val
}

[玩转系统] PowerShell While 循环:回归基础指南

使用内置变量执行 PowerShell While 循环 ($true/$false)

前面的示例在 while 循环中使用条件,效果很好。但您也可以使用 PowerShell 的内置变量(例如 $true$false)来创建 While 循环。

下面的语法将一直执行,直到 $true 不再是 $true。换句话说,循环将永远运行。但您必须始终包含一种打破无限循环的方法。否则,你将永远陷入困境。您将在本教程后面详细了解如何使用 breakcontinue 退出循环。

while($true)
{

	# Code block to execute

}

执行下面的代码块,该代码块将永远运行,并将 $i 的值打印到控制台。

# Declares the $i variable with the initial value of 0
$i = 0

# Sets the While loop to run while the condition is $true
while($true)
{
	# Increments the $i value by 1
	$i++
	
	# Prints the $i variable's current value
	Write-Host $i
}

现在,按 Ctrl+C 打破循环。这个循环会消耗很多系统资源,所以使用时要小心。

[玩转系统] PowerShell While 循环:回归基础指南

执行多条件 While 循环

除了单条件 while 循环之外,您还可以创建多条件 while 循环。与单个条件 While 循环类似,条件必须返回布尔值,即 True 或 False。

下面是多条件 while 循环的语法,与单条件 while 循环的语法类似。主要区别在于您可以包含由以下运算符分隔的多个条件:

  • AND (-and)- 两个条件都必须为真。
  • OR(-or)(任一条件都可以为真)。
# AND operator
while (condition1 -AND condition2)
{

	# Code block to execute

}

# OR operator
while (condition1 -OR condition2)
{

	# Code block to execute

}

执行下面的代码,循环 while $val is not equal (-ne) to 3 -and $i 不等于 (-ne) 5

当两个变量的值达到各自的条件时,循环将中断,并继续执行脚本的其余部分。

# Declares the $val and $i variables with initial values of 0
$val = 0
$i = 0

# Sets the While loop to execute until $val is equal to 3 and $i is equal to 5
while($val -ne 3 -and $i -ne 6)
{
	# Increments $val by 1
  $val++
	# Increments $i by 2
  $i += 2
	# Prints $val and $i variables' current value
  Write-Host "$val, $i"
}

[玩转系统] PowerShell While 循环:回归基础指南

使用 AND 运算符执行 while 循环

[玩转系统] PowerShell While 循环:回归基础指南

现在,执行以下代码,该代码询问用户的年龄,并将其存储在 $age 变量中。

如果用户输入的数字小于 (-lt) 1 或不是数字 (-nomatch),则会再次提示用户输入有效的号码。此行为对于为用户提供多次输入有效输入的机会很有用。

# Prompts the users to enter their age
$age = Read-Host "Please Enter Your Age"

# Sets the While loop to run until the user provides a valid input
while($age -notmatch "\d+" -or $age -lt 1)
{
	# Re-prompts the user to enter a valid age number
  $age = Read-Host "Please Enter Your Valid Age"
}
# Prints the valid age input
Write-Host "Your age is $age

在下面的输出中,您可以看到系统提示用户输入年龄 3 次,如下所示:

  • 第一次,用户输入,这不是数字。
  • 第二次,用户输入 0,它小于 1。
  • 第三次,用户输入10,这是一个有效的年龄。

[玩转系统] PowerShell While 循环:回归基础指南

在 While 循环中使用 BREAK 和 CONTINUE 关键字

您已经了解了 while 循环如何为 PowerShell 脚本添加灵活性。但为了更好地控制 While 循环的执行,请添加 breakcontinue 关键字。

例如,如果您只想处理数组中的一定数量的项目,则可以使用 BREAK 关键字在处理完所需数量的项目后退出循环。

这些关键字的作用如下:

break

立即退出循环并继续执行脚本的其余部分。

continue

跳过当前循环迭代中的剩余代码块并继续下一次迭代。

执行下面的代码,该代码循环遍历包含 10 个项目的数组。

在下面的代码中,if 语句检查 $i 的值。如果 $i 的值为 5,则 continue 关键字会跳过循环中的剩余代码并继续下一次迭代。如果 $i 的值为 8,则 break 关键字将退出循环并继续执行脚本的其余部分。

否则,while 循环将打印 (Write-Host) 并将 $i 变量的值增加 1

# Declares an $array of 10 items
$array = 1..10
# Declares the $i variable with the initial value of 0
$i = 0
# Sets the While look to execute until the condition is met
while($i -lt $array.Count)
{
	# Checks if $i equals 5
  if($i -eq 5)
  {
		# If yes, increment $i by 1
    $i++
		# Continue with the next iteration
    continue
  }
	# Checks if $i equals 8
  if($i -eq 8)
  {
		# If yes, break the While loop and continue with the rest of the script
    break
  }
	# Prints the current value of $i
  Write-Host "Processing item $i"
	# Increments $1 by 1
  $i++
}

正如您在下面的输出中看到的,循环跳过了数组中的第五和第八项。 while 循环处理了数组中的所有其他项目,并在到达第八个项目后退出。

[玩转系统] PowerShell While 循环:回归基础指南

限制 While 循环运行的时间

通常,您可能希望限制循环运行的时间。也许您正在尝试连接到远程服务器。如果是这样,您可以在 while 循环中使用 Start-Sleep cmdlet,让服务器有时间在超时和退出循环之前做出响应。

Start-Sleep cmdlet 将脚本的执行暂停指定的时间。

执行以下代码以获取当前日期和时间 Get-Date 并将其存储在 $startTime 变量中。当当前日期/时间距 $startTime 中存储的值小于 10 秒时,while 循环就会运行。

while 循环运行时,会打印一条消息,同时 Start-Sleep cmdlet 将脚本的执行暂停 1 秒。

下面的代码块只是您在实践中实际使用的样板。您可以根据需要在循环内的代码中添加更多内容。

# Get and store the current date/time
$startTime = Get-Date
# Sets the While loop to run while the current date/time is less than 10 seconds 
	# from the value stored in $startTime.
while((Get-Date) -lt ($startTime.AddSeconds(10)))
{
	# Prints a message
  Write-Host "Waiting for server to respond..."
	# Pauses the script for one second
  Start-Sleep -Seconds 1
}

下面,您可以看到循环在退出循环之前继续运行了 10 秒。

[玩转系统] PowerShell While 循环:回归基础指南

结论

当遇到复杂的概念时,PowerShell while 循环会派上用场,以避免陷入循环或编写脚本时。在本教程中,您学习了许多使用 while 循环来实现更灵活、更强大的脚本的方法。

有了这些新发现的知识,天空才是极限。那么为什么不最大限度地使用逻辑运算符和关键字来通过脚本自动执行任务呢?

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

取消回复欢迎 发表评论:

关灯