Skip to content

Instantly share code, notes, and snippets.

@egil
Created March 20, 2023 12:04
Show Gist options
  • Save egil/59242fb8230741e96877b64430f7f04b to your computer and use it in GitHub Desktop.
Save egil/59242fb8230741e96877b64430f7f04b to your computer and use it in GitHub Desktop.
A PowerShell helper function that will invoke a script block a number of times until it completes successfully, with a configurable delay between retries.
function Invoke-With-Retry {
[CmdletBinding()]
Param(
[Parameter(Position = 0, Mandatory = $true)]
[scriptblock]$ScriptBlock,
[Parameter(Position = 1, Mandatory = $false)]
[int]$Retries = 5,
[Parameter(Position = 2, Mandatory = $false)]
[int]$DelayInMilliseconds = 100
)
Begin {
$count = 0
}
Process {
do {
$count++
$output = $null
try {
$output = Invoke-Command -Command $ScriptBlock -ErrorVariable err -ErrorAction Stop
if ($err.Count -gt 0) {
throw $errors
}
if ($LastExitCode -gt 0) {
throw $output
}
return $output
}
catch {
# A ScriptTerminatedException is thrown when a PowerShell script is terminated by an
# external process or action, such as a user pressing Ctrl+C or a system shutdown.
if ($_.Exception.GetType().Name -eq "ScriptTerminatedException") {
return
}
Start-Sleep -Milliseconds $DelayInMilliseconds
}
} while ($count -lt $Retries)
Write-Warning "Failed to execute script block successfully. The maximum number of retries ($Retries) exceeded."
return $output
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment