Skip to content

Instantly share code, notes, and snippets.

@abhipalsingh
Last active December 29, 2023 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhipalsingh/84807bfd1fc32a2023b7aa0cedf976ee to your computer and use it in GitHub Desktop.
Save abhipalsingh/84807bfd1fc32a2023b7aa0cedf976ee to your computer and use it in GitHub Desktop.
Powershell Modules

Usage:

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment