Powershell 在 If else 语句中执行 while 循环

Powershell Do while loop with inside If else statement

我想开发一个循环,如果错误被捕获,并尝试 3 次,然后停止并退出。

问题是如何让循环计数3次后停止? 谢谢

Powershell 代码


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

在 try 块的开头插入以下内容:

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

break会导致powershell退出循环

我会将其重写为 for 循环以获得更清晰的代码:

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

只看第一行,我们可以清楚地看出这是一个计数循环。它还让我们摆脱了一个变量,因此我们拥有更少的状态,使代码更容易理解。

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

i is 3