Skip to content

Instantly share code, notes, and snippets.

@kerslake
Last active February 1, 2017 06:31
Show Gist options
  • Save kerslake/e917df9ff6bf5cd9f39e to your computer and use it in GitHub Desktop.
Save kerslake/e917df9ff6bf5cd9f39e to your computer and use it in GitHub Desktop.
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
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)
Start-Sleep $secondsDelay
$retrycount++
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment