0

I'm somewhat of a PowerShell beginner, and I'm struggling to get my code to break out of a For loop. More specifically, my $parseCount Variable is always being reset to "1" when calling $ParseCount++, even if some pre-existing conditions meant that its value was original "2". Therefore, I keep getting stuck in an infinite loop.

In the below example, the script correctly deduces which level of "work" should be done, on the first pass. But then it'll always set the $ParseCount variable to 1, instead of to $ParseCount + 1.

I'm sure it's something easy. Thanks in advance for helping!

# 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

}

Sample output:

ParseCount variable is: 2 ParseCount was changed, is now set to 1

2
  • The line If ($ParseCount=0) is setting $ParseCount to 0. You need to change it to If($ParseCount -eq 0). Also checkout powershell comparision docs
    – Vish
    May 19, 2020 at 12:37
  • Typically you'd use the for itself to perform the increment with For ( ; $ParseCount -lt 3; $ParseCount++) { }. Also, you don't need to check on every iteration if the prerequisites for the entire loop have been met, so you can simplify and optimize that to If ($ParseCount -eq 0) { Write-Host "I'm doing some prerequisite stuff" } For ( ; $ParseCount -lt 3; $ParseCount++) { Write-Host "I'm doing all of the work, because prerequisite is done" }. See Introducing the for-if anti-pattern. May 19, 2020 at 17:11

1 Answer 1

2

You should change

    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"
                           }

(which would set $ParseCount back to 0)

into

    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"
                           }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.