使用基本结构:
try
{
Do-Something
}
catch
{
Write-Output "Something threw an exception"
}
是否可以继续尝试“Do-Something”直至成功?也许使用像这样的 while 循环:
$Timeout = 60
$timer = [Diagnostics.Stopwatch]::StartNew()
$t = 0
while (($timer.Elapsed.TotalSeconds -lt $Timeout) -and ($t -ne 1))) {
Start-Sleep -Seconds 1
try
{
Do-Something
$t = 1
}
catch
{
Write-Output "Something threw an exception"
}
}
$timer.Stop()
这里我使用计时器来确保 PowerShell 不会无限期地运行。
它应该继续尝试,直到 try
成功并且 $t = 1
被执行。然而,大约2秒后就失败了。请帮忙。
更具体地说,Do-Something 是:
(Get-Process -Name FineReader).MainWindowHandle
我希望代码继续尝试,直到 FineReader
存在并且它可以获取 MainWindowHandle
。
最佳答案
您可以使用break
关键字。
# Set the erroracton preference to stop when an error occurs,
$ErrorActionPreferenceBak = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
While($True){
try{
Do-Something
break
}
catch{
Write-Output "Something failed"
Start-Sleep -Seconds 1 # wait for a seconds before next attempt.
}
finally{
#Reset the erroracton preference
$ErrorActionPreference = $ErrorActionPreferenceBak
}
}
关于windows - 如何在powershell中不断尝试某件事直到成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52403643/