Skip to content

Instantly share code, notes, and snippets.

@mill5james
Created November 5, 2018 13:09
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 mill5james/22651ec6d880056cb04917b61ac08dc0 to your computer and use it in GitHub Desktop.
Save mill5james/22651ec6d880056cb04917b61ac08dc0 to your computer and use it in GitHub Desktop.
PowerShell Retry
function Retry-Command
{
param (
[Parameter(Mandatory=$true)][string]$command,
[Parameter(Mandatory=$true)][hashtable]$args,
[Parameter(Mandatory=$false)][int]$retries = 5,
[Parameter(Mandatory=$false)][int]$secondsDelay = 2
)
# Setting ErrorAction to Stop is important. This ensures any errors that occur in the command are
# treated as terminating errors, and will be caught by the catch block.
$args.ErrorAction = "Stop"
$retrycount = 0
$completed = $false
$printArgs = ($args.GetEnumerator() | %{ "-$($_.Name) $($_.Value -join ' ')"}) -join ' '
while (-not $completed) {
try {
& $command @args
Write-Verbose ("Command [{0}] succeeded." -f $command)
$completed = $true
} catch {
if ($retrycount -ge $retries) {
Write-Verbose ("Command [{0}] failed the maximum number of {1} times." -f $command, $retrycount)
throw
} else {
Write-Verbose ("Command [{0}] failed. Retrying in {1} seconds." -f $command, $secondsDelay)
$retrycount++
Write-Progress -Activity "Trying command ""$command $printArgs""" -Status "Retry $retrycount of $retries" -PercentComplete (($retrycount / $retries) * 100) -SecondsRemaining (($retries * $secondsDelay) - ($retrycount * $secondsDelay))
Start-Sleep $secondsDelay
}
}
}
Write-Progress -Activity "Retrying $command $printArgs" -Completed
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment