Place ExponentialBackoff.psm1 file along with your powershell script and pass commands to Exponential Back Off function.
using module ".\ExponentialBackoff.psm1"
Use-ExponentialBackoff -ScriptBlock { Your script here. }
function Use-ExponentialBackoff { | |
[CmdletBinding()] | |
param ( | |
[Parameter(Mandatory = $true)] | |
[scriptblock] | |
$ScriptBlock, | |
[Parameter(Mandatory = $false)] | |
[int] | |
[ValidateRange(1, 100)] | |
$MaxRetries = 10, | |
[Parameter(Mandatory = $false)] | |
[int] | |
[ValidateRange(2, 1024)] | |
$MaxRetryDelay = 128 | |
) | |
$retryCount = 0 | |
while ($true) { | |
try{ | |
. $ScriptBlock -ErrorAction Stop | |
break | |
} | |
catch { | |
if($retryCount++ -lt $MaxRetries) { | |
$sleeptime = If($sleeptime -lt $MaxRetryDelay) { ([Math]::Pow(2, $retryCount)) } Else { $sleeptime } | |
Write-Host "$($_.exception) `nRetry $retryCount after $sleeptime seconds" | |
Start-Sleep $sleeptime | |
} | |
else { | |
throw | |
} | |
} | |
} | |
} | |
Export-ModuleMember -Function Use-ExponentialBackoff |