简体   繁体   中英

Powershell Do while loop with inside If else statement

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

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

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.

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

i is 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM