Search code examples
windowspowershellscriptingpowershell-3.0powershell-4.0

How to continuously try something in powershell until it succeeds?


Using the basic construct:

try
{
    Do-Something
}
catch
{
    Write-Output "Something threw an exception"
}

Is it possible to keep trying the Do-Something until it succeeds? Perhaps using a while loopp like this:

$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()

Here I use a timer to make sure PowerShell doesn't run indefinitely. It should keep trying until the try succeeds and $t = 1 is executed. However, it fails in about 2 seconds. Please help.

More specifically the Do-Something is:

(Get-Process -Name FineReader).MainWindowHandle

I'd like the code to keep trying until FineReader exists and it can get the MainWindowHandle.


Solution

  • You can use break keyword.

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