For 循环是任何编程语言中(valuable tools in any programming language)最有价值的工具之一, Microsoft PowerShell也不例外。您可以使用其他循环来重复命令,但 For 循环可能是最直接的。
从迭代数组到执行预定次数的函数,您可以使用此工具实现许多目标。这是有关如何在PowerShell中使用 For 循环的教程。
PowerShell中 For循环(Loops)的用途(Use)是什么?
与命令提示符(Command Prompt)不同,PowerShell是一个完整的脚本环境。这意味着您可以编写可重用的PowerShell 脚本(PowerShell scripts)来自动执行任务,而不是手动输入命令。而 For 循环是编写这些模块的关键。
For 语句将脚本块重复特定次数,修改给定变量以跟踪进度。这允许您将循环用于一些相当有趣的场景。
您可以生成数字序列、确定质数或显示倒数计时器。更实际地,您可以遍历对象数组,对每个条目执行一些操作。
PowerShell中For循环(Loop)的语法(Syntax)
For 循环在Windows PowerShell中的工作方式与它们在任何编程语言中的工作方式相同。初始化跟踪变量、测试其值和修改变量的表达式包含在“For”后面的括号内,用分号分隔。然后是由大括号绑定的语句列表本身。
对于(初始化(Initialization);条件(Condition);更新(Update))
{
脚本块(Script Block)
}
如何在PowerShell 脚本中使用 For(PowerShell Script)循环(Loop)
使用 For 循环非常简单。每当您遇到需要重复稍微变化的步骤的情况时,您都应该将其放入 For 循环中。
假设您需要编写一个代码片段,它可以找到所有自然数的总和,直到一个数字n包含在变量 $n 中。这是一个基本的 For 循环示例:
$n = 10
$总和 = 0
对于 ($i = 1 ; $i -le $n ; $i++)
{
$sum = $sum + $i
}
“$n 个自然数之和是 $sum”
通过 For 循环访问数组
生成数字序列几乎不是大多数人使用PowerShell的目的。更常见的用法是遍历数组。
假设(Say)您有一个包含七个元素的数组 $week。您可以使用简单的 For 循环输出数组中包含的日期列表,如以下示例所示。
对于 ($i = 0 ; $i -lt $week.Length ; $i++)
{
$周[$i]
}
使用ForEach 循环(ForEach Loop)快速(Quickly Iterate)遍历数组
For 循环的另一种形式是ForEach语句。此版本简化了遍历PowerShell数组的内容并单独处理它们。例如,前面的代码片段可以这样重写:
Foreach ($day in $week)
{
$天
}
在处理更复杂的对象时,您还可以使用 Foreach-Object cmdlet 对任何PowerShell命令的内容执行操作。
For循环与(Loop Different)其他类型(Types)的循环(Loops)有何不同?
For 循环不是您可以使用的唯一循环语句类型。与大多数编程语言一样,PowerShell具有多种类型的循环。
尽管
其中最简单的是 While 循环。您所拥有的只是一个条件和一个脚本块,只要测试表达式的计算结果为真,循环就会运行。由于首先计算表达式,因此代码有可能根本不运行或最终成为无限循环。
而(条件(Condition))
{
脚本块(Script Block)
}
Do-While
如果您正在编写一个至少需要运行一次的脚本——即使表达式的计算结果为假——那么您可以使用Do-While循环。与 While 循环的唯一区别是它将命令块放在条件之前,这意味着代码在第一次检查测试表达式之前执行。
做 {
脚本块(Script block)
}
而(条件(Condition))
做-直到
此循环的另一个版本是Do-Until。基本上(Basically),它运行代码块,然后重复它,直到测试表达式为真——与Do-While循环相反。不是一个特别有用的结构,因为您可以通过修改标准Do-While(Do-While)循环中的条件来实现相同的目的。
做 {
脚本块(Script Block)
}
直到(条件(Condition))
为什么 For 循环更好
所有这些其他循环结构的问题在于它们不包括初始值或更新语句。您必须手动记住在循环外创建一个变量,然后在循环的每次通过期间递增(或递减)它。
正如您所料,程序员经常忘记这一步,导致脚本无法按预期工作。这浪费了宝贵的调试时间。
For 循环通过需要在起始括号内初始化和递增表达式来避免这个问题。这会导致更清晰、更健壮的脚本。
什么时候应该在PowerShell中使用 For循环(Loop)?
PowerShell就是为自动化创建脚本。实现这一点的最有用的工具可能是 For 循环。您可以使用它用更紧凑、更优雅的脚本替换许多复制粘贴操作。
这个循环最常见的功能是遍历一个数组,一次一个条目。对于更精简的脚本,您也可以使用ForEach循环。您也可以使用 For 循环来生成数字序列,尽管这很少需要。
For 循环通过将循环的所有基本功能都包含在参数中来比其他循环算法得分,从而防止由于忘记这些语句而导致的任何错误。这使得 For 循环在任何需要重复一组命令的场景中都是必不可少的。
How a PowerShell For Loop Can Run a Command Multiple Times
The For loop is one of the moѕt valuable tools in any programming language, and Microsoft PowerShell is no different. You can use other loops to repeat commands, but the For loop is perhaps the most straightforward.
From iterating over arrays to carrying out a function a predetermined number of times, there are many things you can achieve with this tool. Here is a tutorial on how to use For loops in PowerShell.
What Is the Use of For Loops in PowerShell?
Unlike Command Prompt, PowerShell is a complete scripting environment. This means you can write reusable PowerShell scripts to automatically carry out tasks rather than entering commands manually. And For loops are the key to writing these modules.
A For statement repeats a script block a specific number of times, modifying a given variable to keep track of progression. This allows you to use the loop for some rather interesting scenarios.
You can generate sequences of numbers, determine a prime number, or display a countdown timer. More practically, you can iterate over an array of objects, performing some action with each entry.
The Syntax of a For Loop in PowerShell
For loops work in Windows PowerShell the same way they do in any programming language. Expressions initializing the tracking variable, testing its value, and modifying the variable are ensconced within the brackets following “For,” separated by semicolons. Then comes the statement list itself bound by curly braces.
For (Initialization; Condition; Update)
{
Script Block
}
How to Use the For Loop in a PowerShell Script
Using the For loop is pretty simple. Whenever you encounter a situation that calls for repeating a slightly varying step, you should put it into a For loop.
Let’s say you need to write a code snippet that can find the sum of all natural numbers until a number n, contained in the variable $n. Here is a basic For loop example:
$n = 10
$sum = 0
For ($i = 1 ; $i -le $n ; $i++)
{
$sum = $sum + $i
}
“The sum of $n natural numbers is $sum”
Accessing Arrays Through a For Loop
Generating numeric sequences is hardly what most people use PowerShell for. A more common usage is to iterate over an array.
Say you have an array $week with seven elements. You can output the list of the days contained in the array using a simple For loop, as demonstrated in the following example.
For ($i = 0 ; $i -lt $week.Length ; $i++)
{
$week[$i]
}
Using the ForEach Loop To Quickly Iterate Through an Array
Another form of the For loop is the ForEach statement. This version simplifies going through the contents of a PowerShell array and processing them individually. The previous code snippet, for example, can be rewritten like this:
Foreach ($day in $week)
{
$day
}
When dealing with more complex objects, you can also use the Foreach-Object cmdlet to perform an action on the contents of any PowerShell command.
How is the For Loop Different From Other Types of Loops?
The For loop isn’t the only type of looping statement available to you. Like most programming languages, PowerShell has multiple types of loops.
While
The simplest of these is the While loop. All you have is a condition and a script block, and the loop runs as long as the test expression evaluates to true. Since the expression is evaluated first, there is a chance for the code not to run at all or end up as an infinite loop.
While (Condition)
{
Script Block
}
Do-While
If you are writing a script that needs to run at least once – even if the expression evaluates to false—then you can use the Do-While loop. The only difference from the While loop is that it places the command block before the condition, which means that the code is executed before the test expression is checked for the first time.
Do {
Script block
}
While (Condition)
Do-Until
Another version of this loop is Do-Until. Basically, it runs the code block and then repeats it until the test expression is true – the reverse of a Do-While loop. Not a particularly useful structure, as you can achieve the same thing by modifying the condition in a standard Do-While loop.
Do {
Script Block
}
Until (Condition)
Why the For Loop is Better
The problem with all these other looping structures is that they do not include the initial value or update statements. You have to manually remember to create a variable outside the loop and then increment it (or decrement it) during every pass of the loop.
As you might expect, programmers often forget this step, leading to a script that doesn’t work as intended. This wastes precious time in debugging.
The For loop avoids this issue by necessitating the initialization and increment expressions within the starting brackets. This leads to cleaner, more robust scripts.
When Should You Use the For Loop in PowerShell?
PowerShell is all about creating scripts for automation. And probably the most useful tool for achieving this is the For loop. You can use it to replace many copy-paste operations with a more compact, elegant script.
The most common function of this loop is to iterate over an array, one entry at a time. For an even more streamlined script, you can use a ForEach loop as well. You can also use the For loop to generate numerical sequences, although that is rarely needed.
The For loop scores over other looping algorithms by including all essential functions of a loop into the parameters, preventing any errors due to forgetting those statements. This makes the For loop indispensable in any scenario calling for repeating a set of commands.