powershell - 为什么在 PowerShell 中的 for 循环中省略变量会导致无限循环?

标签 powershell powershell-4.0

为什么

 $i=1
 for ($i -le 5; $i++)
 {Write-Host $i}

导致无限循环? 我从来没有尝试过用 C# 或任何其他编程语言编写这样的东西,所以我不知道它在那里会如何表现,但为什么 for 循环不只是捕获“i”变量将其与 5 进行比较,加 1再比较一下,这就像 for 循环是盲目的或者某种形式的机器,而不是一个理性的、有逻辑的人。

为什么是无限而不只是获取预定义的 i? 像“因为这就是 PowerShell 的功能”之类的答案毫无用处,我想知道为什么它会这样工作。

我知道它变得无限,因为它缺少第一个参数,但我想知道为什么,就像哲学上的答案“为什么 for 循环不寻找 the 的变量”在其循环之外具有相同的名称,但必须明确包含在其中?”

最佳答案

如果您阅读 Windows PowerShell 语言规范,您将看到 for 语句的语法:

for-statement:
for   new-linesopt   (
        new-linesopt   for-initializeropt   statement-terminator
        new-linesopt   for-conditionopt   statement-terminator
        new-linesopt   for-iteratoropt
        new-linesopt   )   statement-block
for   new-linesopt   (
        new-linesopt   for-initializeropt   statement-terminator
        new-linesopt   for-conditionopt
        new-linesopt   )   statement-block
for   new-linesopt   (
        new-linesopt   for-initializeropt
        new-linesopt   )   statement-block
for-initializer:
pipeline
for-condition:
pipeline
for-iterator:
pipeline

这意味着在您的示例中,第一个语句是 INITIALIZER

如果你这样重写循环:

$i=1
for (;$i -le 5; $i++)
{Write-Host $i}

它将按您的预期工作。 注意附加的“;”。

如果省略“;”,在上面的语法中,$i++ 对应于 for-condition,它不断地计算为 $true,因此循环永远不会结束。

关于powershell - 为什么在 PowerShell 中的 for 循环中省略变量会导致无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27979890/

相关文章:

powershell - 如何从Powershell修改COM +应用程序

Powershell - 检查 CD 是否在 CD-ROM 驱动器中

powershell - 检查列表以查看文件是否存在于 powershell 中?

powershell - 调用ConvertTo-Csv后无法将简单对象保存为CSV

powershell - 将类的输出写入文本文件会添加空行

powershell - Powershell选择唯一字段

powershell - 如何在powershell中获取目录中不同文件的数量?

powershell - * .tmp是否存在于目录中,如何不对目录进行操作?

powershell - 如何在表 powershell 中显示可用位置

sql-server-2012 - PowerShell 4 安装后 Invoke-Sqlcmd 不起作用