Last active
February 1, 2017 06:31
-
-
Save kerslake/e917df9ff6bf5cd9f39e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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