首页 > 解决方案 > Powershell 基础 - 递增变量以管理循环

问题描述

我有点像 PowerShell 初学者,我正在努力让我的代码跳出 For 循环。更具体地说,我的$parseCount变量在调用时总是被重置为“1” $ParseCount++,即使某些预先存在的条件意味着它的值是原始的“2”。因此,我一直陷入无限循环。

在下面的示例中,脚本在第一遍时正确推断出应该完成的“工作”级别。但是它总是将 $ParseCount 变量设置为 1,而不是设置为 $ParseCount + 1。

我敢肯定这很容易。提前感谢您的帮助!

# all possible Scenarios

 If ($Scenario -ieq "Outcome1") {
                      $ParseCount=0
                      }

If ($Scenario -ieq "Outcome2") {
$ParseCount=1
}

If ($Scenario -ieq "Outcome3") {
                      $ParseCount=2
                      }

# Start the loop

For ($ParseCount -lt 3){

# determine what work to do

    If ($ParseCount=0){
             write-host "I'm doing some prerequisite stuff"
                }

    If ($ParseCount -gt 0){
             write-host "I'm doing all of the work, beacause prerequisite is done"
                           }

# Return to the top of the loop

write-host "ParseCount variable is:", $ParseCount
$ParseCount++
write-host "ParseCount was changed, is now set to:", $ParseCount

}

样本输出:

ParseCount 变量是:2 ParseCount 已更改,现在设置为 1

标签: powershellfor-loopincrement

解决方案


你应该改变

    If ($ParseCount=0){
             write-host "I'm doing some prerequisite stuff"
                }

    If ($ParseCount -gt 0){
             write-host "I'm doing all of the work, beacause prerequisite is done"
                           }

(这将设置$ParseCount回 0)

进入

    If ($ParseCount -eq 0){
             write-host "I'm doing some prerequisite stuff"
                }

    If ($ParseCount -gt 0){
             write-host "I'm doing all of the work, beacause prerequisite is done"
                           }


推荐阅读