Last active
September 4, 2024 15:14
-
-
Save gwalkey/c6d889884c3bb4a835c99f65b4d39ab6 to your computer and use it in GitHub Desktop.
Powershell Anonymous Lamda for Retry with Exponential Backoff
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
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
Line 33 needs to be replaced with the following code:
Start-Sleep -Seconds $retryDelaySeconds