Skip to content

Instantly share code, notes, and snippets.

@gwalkey
Last active September 4, 2024 15:14
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 -Seconds $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
@gwalkey
Copy link
Author

gwalkey commented Sep 4, 2024

Line 33 needs to be replaced with the following code:

Start-Sleep -Seconds $retryDelaySeconds

Done!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment