PowerShell Retry with Exponential Backoff and Jitter
PowerShell
function Invoke-WithRetry {
[CmdletBinding()]
param(
[Parameter(Mandatory)][scriptblock]$Action,
[int]$MaxAttempts = 5,
[double]$BaseDelay = 0.5,
[double]$MaxDelay = 30
)
for ($attempt = 1; ; $attempt++) {
try { return & $Action }
catch {
if ($attempt -ge $MaxAttempts) { throw }
$expo = [Math]::Min($MaxDelay, $BaseDelay * [Math]::Pow(2, $attempt - 1))
$delay = $expo * (0.5 + [Random]::new().NextDouble() / 2) # 50-100% jitter
Start-Sleep -Milliseconds ([int]($delay * 1000))
}
}
}