Home > Software design >  Powershell Do while loop with inside If else statement
Powershell Do while loop with inside If else statement

Time:09-25

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

CodePudding user response:

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

  • Related