Skip to content

Instantly share code, notes, and snippets.

@zachbonham
Last active December 12, 2015 12:49
Show Gist options
  • Save zachbonham/4774553 to your computer and use it in GitHub Desktop.
Save zachbonham/4774553 to your computer and use it in GitHub Desktop.
Retriable implementation in PowerShell completely ripped off from an implementation in Ruby.
# complete rip off of http://blog.mirthlab.com/2012/05/25/cleanly-retrying-blocks-of-code-after-an-exception-in-ruby/
#
# usage
# retriable -tries 5 -action { do-work-that-could-throw-exception }
#
function retriable($tries=3, $interval=1, [scriptblock]$action)
{
$retry_count = 1
$the_exception = $null
do
{
$is_error = $false
try
{
& $action
# reset in case it worked this last try
#
$is_error = $false
}
catch
{
#cache off exception to throw if we've exhausted our retries
#
$the_exception = $_
$is_error = $true
write-debug "[retriable] caught exception"
write-debug "[retriable] attempt $retry_count of $tries failed, trying again"
if ( $retry_count -ge $tries )
{
write-debug "[retriable] exhausted $retry_count retry attempts"
}
else
{
write-debug "[retriable] waiting $interval seconds"
sleep -seconds $interval
}
}
$retry_count = $retry_count + 1
} while($is_error -eq $true -and $retry_count -le $tries)
if ( $is_error )
{
throw $the_exception
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment