Skip to content

Instantly share code, notes, and snippets.

@gwalkey
Last active October 26, 2021 16:09
Show Gist options
  • Save gwalkey/c6d889884c3bb4a835c99f65b4d39ab6 to your computer and use it in GitHub Desktop.
Save gwalkey/c6d889884c3bb4a835c99f65b4d39ab6 to your computer and use it in GitHub Desktop.
Powershell Anonymous Lamda for Retry with Exponential Backoff
# https://vexx32.github.io/2018/10/26/Anonymous-Functions/
function Retry()
{
param(
[Parameter(Mandatory=$true)][Action]$action,
[Parameter(Mandatory=$false)][int]$maxAttempts = 3
)
$attempts=1
$ErrorActionPreferenceToRestore = $ErrorActionPreference
$ErrorActionPreference = "Stop"
do
{
try
{
$action.Invoke();
break;
}
catch [Exception]
{
Write-Host $_.Exception.Message
}
# exponential backoff delay
$attempts++
if ($attempts -le $maxAttempts)
{
$retryDelaySeconds = [math]::Pow(2, $attempts)
$retryDelaySeconds = $retryDelaySeconds - 1 # Exponential Backoff Max == (2^n)-1
Write-Host("Action failed. Waiting " + $retryDelaySeconds + " seconds before attempt " + $attempts + " of " + $maxAttempts + ".")
Start-Sleep -Milliseconds $retryDelaySeconds
}
else
{
$ErrorActionPreference = $ErrorActionPreferenceToRestore
Write-Error $_.Exception.Message
}
} while ($attempts -le $maxAttempts)
$ErrorActionPreference = $ErrorActionPreferenceToRestore
}
function MyFunction($inputArg)
{
Throw $inputArg
}
# #Example of a call:
Retry({MyFunction "Oh no! It happened again!"})
Retry {MyFunction "Oh no! It happened again!"} -maxAttempts 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment