0

I would like to develop a looping which if the error was caught, and attempts 3 times, then stop and exit.

The question is how to make the loop count 3 times and stop it? Thanks.

Powershell Code


function loop() {

$attempts = 0
$flags = $false

do {

    try {

        Write-Host 'Updating...Please Wait!'
    
         ***Do something action***

        Write-Host 'INFO: Update Completed!' -BackgroundColor BLACK -ForegroundColor GREEN

        Start-Sleep 1
        
        $flags = $false
        
} catch {

        Write-Host 'Error: Update Failure!' -BackgroundColor BLACK -ForegroundColor RED
        
        $attempts++
        
        $flags = $true
        
        Start-Sleep 2
    
        }
    
    } while ($flags)
    
} 

3 Answers 3

4

Insert the following at the start of your try block:

        if($attempts -gt 3){
            Write-Host "Giving up";
            break;
        }

break will cause powershell to exit the loop

Sign up to request clarification or add additional context in comments.

Comments

1

I would rewrite this as a for-loop for clearer code:

foreach( $attempts in 1..3 ) {
    try {

        Write-Host 'Updating...Please Wait!'
    
         ***Do something action***

        Write-Host 'INFO: Update Completed!' -BackgroundColor BLACK -ForegroundColor GREEN

        Start-Sleep 1
        
        break   # SUCCESS-> exit loop early
        
    } catch {

        Write-Host 'Error: Update Failure!' -BackgroundColor BLACK -ForegroundColor RED
   
        Start-Sleep 2  
    }    
}

From just looking at the first line, we can clearly see that this is a counting loop. It also lets us get rid of one variable so we have less state, making the code easier to comprehend.

Comments

1
$i = 0
if ( $(do { $i++;$i;sleep 1} while ($i -le 2)) ) { 
  "i is $i" 
}

i is 3

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.