scott
scott

Reputation: 3

Powershell basics - incrementally increase a variable to manage a loop

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

Upvotes: 0

Views: 286

Answers (1)

Peter Pesch
Peter Pesch

Reputation: 643

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

Upvotes: 2

Related Questions