Last active
March 5, 2018 23:17
-
-
Save alex-titarenko/a6f552b53abc1a6dcce4b61a2602f39f to your computer and use it in GitHub Desktop.
Retry-Command
This file contains hidden or 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 = 5, | |
[Parameter(Mandatory = $false)][string]$Name = "" | |
) | |
# 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; | |
$displayName = if ($Name) { $Name } else { $Command } | |
while (-not $completed) { | |
try { | |
$result = & $Command @Args; | |
Write-Host "Command [$displayName] succeeded."; | |
$completed = $true; | |
return $result; | |
} catch { | |
$errorMessage = $_.Exception.Message; | |
if ($retrycount -ge $Retries) { | |
Write-Host "Command [$displayName] failed the maximum number of $retrycount times."; | |
throw; | |
} else { | |
Write-Host "Command [$displayName] failed. Message: $errorMessage. Retrying in $SecondsDelay seconds."; | |
Start-Sleep $SecondsDelay; | |
$retrycount++; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment