Skip to main content

PowerShell function to execute a command with retry support.

function Execute-WithRetry([ScriptBlock] $command)
{
    $attemptCount = 0
    $operationIncomplete = $true
    $maxFailures = 5
    $sleepBetweenFailures = 1

    while ($operationIncomplete -and $attemptCount -lt $maxFailures)
    {
        $attemptCount = ($attemptCount + 1)

        if ($attemptCount -ge 2)
        {
            Write-Host "Waiting for $sleepBetweenFailures seconds before retrying..."
            Start-Sleep -s $sleepBetweenFailures
            Write-Host "Retrying..."
        }

        try
        {
            # Call the script block
            & $command

            $operationIncomplete = $false
        }
        catch [System.Exception]
        {
            if ($attemptCount -lt ($maxFailures))
            {
                Write-Host ("Attempt $attemptCount of $maxFailures failed: " + $_.Exception.Message)
            }
            else
            {
                throw
            }
        }
    }
}


# -----------------------------------------------------------------------
# Example Usage:
# -----------------------------------------------------------------------

# Start App Pool
Execute-WithRetry
{
    $state = Get-WebAppPoolState $applicationPoolName
    if ($state.Value -eq "Stopped")
    {
        Write-Host "Application pool is stopped. Attempting to start..."
        Start-WebAppPool $applicationPoolName
    }
}


#
# Similar pattern used here:
# https://github.com/ewoutkramer/fhir-net-api/blob/master/build/build.ps1