Created
November 5, 2018 13:09
-
-
Save mill5james/22651ec6d880056cb04917b61ac08dc0 to your computer and use it in GitHub Desktop.
PowerShell Retry
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 | |
$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