Skip to content

Instantly share code, notes, and snippets.

@JKerens
Created July 28, 2022 17:57
Show Gist options
  • Select an option

  • Save JKerens/a77a4cd61585e400a5f9662f49c74b77 to your computer and use it in GitHub Desktop.

Select an option

Save JKerens/a77a4cd61585e400a5f9662f49c74b77 to your computer and use it in GitHub Desktop.
PowerShell Retry Wrapper
function WithRetry {
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[ValidateNotNull()]
[ScriptBlock] $Command,
[Parameter(Mandatory = $false)]
[int]$RetryCount = 3
)
Write-Host "Retry Injection Scope"
$i = 0
do {
try {
return Invoke-Command $Command
}
catch {
Write-Host "Retry #$((++$i))" -fore Red
}
} until ($i -ge $RetryCount)
}
function Invoke-FlakyCommand {
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[int]$Number
)
# Retries the command on transient errors.
WithRetry {
if (Get-Random -InputObject $true, $false) {
throw "Oooops"
}
return $Number
}
}
(1..5) | ForEach-Object { $_ | Invoke-FlakyCommand }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment