我想开发一个循环,如果错误被捕获,并尝试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)
} 发布于 2021-09-25 10:14:29
在try块的开头插入以下内容:
if($attempts -gt 3){
Write-Host "Giving up";
break;
}break将导致powershell退出循环。
发布于 2021-09-25 13:22:56
为了获得更清晰的代码,我会将其重写为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
}
}从第一行来看,我们可以清楚地看到这是一个计数循环。它还允许我们去掉一个变量,使我们拥有更少的状态,从而使代码更易于理解。
发布于 2021-09-25 14:45:47
$i = 0
if ( $(do { $i++;$i;sleep 1} while ($i -le 2)) ) {
"i is $i"
}
i is 3https://stackoverflow.com/questions/69324989
复制相似问题