关于 WhileAbout While

简短说明SHORT DESCRIPTION

描述一个语言语句,您可以使用该语句根据条件测试的结果运行命令块。Describes a language statement that you can use to run a command block based on the results of a conditional test.

详细说明LONG DESCRIPTION

While 语句 (也称为 While 循环) 是一种用于创建循环的语言构造,只要条件测试的计算结果为 true,就会在命令块中运行命令。The While statement (also known as a While loop) is a language construct for creating a loop that runs commands in a command block as long as a conditional test evaluates to true. While 语句的构造比 For 语句更简单,因为它的语法不够复杂。The While statement is easier to construct than a For statement because its syntax is less complicated. 此外,它比 Foreach 语句更灵活,因为您在 While 语句中指定条件测试来控制循环运行的次数。In addition, it is more flexible than the Foreach statement because you specify a conditional test in the While statement to control how many times the loop runs.

下面显示了 While 语句语法:The following shows the While statement syntax:

while (<condition>){<statement list>}

运行 While 语句时,PowerShell 会 <condition> 在输入节之前计算语句的部分 <statement list>When you run a While statement, PowerShell evaluates the <condition> section of the statement before entering the <statement list> section. 语句的条件部分解析为 true 或 false。The condition portion of the statement resolves to either true or false. 只要条件保持为 true,PowerShell 将重新运行该 <statement list> 部分。As long as the condition remains true, PowerShell reruns the <statement list> section.

<statement list>语句的部分包含一个或多个命令,这些命令在每次输入或重复循环时都会运行。The <statement list> section of the statement contains one or more commands that are run each time the loop is entered or repeated.

例如,如果未创建 $val 变量,或者 $val 变量已创建并初始化为0,则以下 While 语句将显示数字1到3。For example, the following While statement displays the numbers 1 through 3 if the $val variable has not been created or if the $val variable has been created and initialized to 0.

while($val -ne 3)
{
    $val++
    Write-Host $val
}

在此示例中,条件 ($val 在 $val = 0、1、2时不等于 3) 为 true。In this example, the condition ($val is not equal to 3) is true while $val = 0, 1, 2. 每次通过循环时,使用 + + 一元增量运算符 ($val) 递增 1 $val + + 。Each time through the loop, $val is incremented by 1 using the ++ unary increment operator ($val++). 上次循环的时间,$val = 3。The last time through the loop, $val = 3. 如果 $val 等于3,则 condition 语句的计算结果为 false,并且循环将退出。When $val equals 3, the condition statement evaluates to false, and the loop exits.

若要在 PowerShell 命令提示符下轻松写入此命令,可以按以下方式输入:To conveniently write this command at the PowerShell command prompt, you can enter it in the following way:

while($val -ne 3){$val++; Write-Host $val}

请注意,分号将添加1的第一个命令与向控制台写入 $val 的第二个命令中的 $val 隔开。Notice that the semicolon separates the first command that adds 1 to $val from the second command that writes the value of $val to the console.

另请参阅SEE ALSO

about_Comparison_Operatorsabout_Comparison_Operators

about_Doabout_Do

about_Foreachabout_Foreach

about_Forabout_For

about_Language_Keywordsabout_Language_Keywords