Skip to content

Instantly share code, notes, and snippets.

@YakDriver
Created February 6, 2018 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YakDriver/a28d6a9e17507068384afd562ae26941 to your computer and use it in GitHub Desktop.
Save YakDriver/a28d6a9e17507068384afd562ae26941 to your computer and use it in GitHub Desktop.
Retry-TestCommand
function Retry-TestCommand
{
param (
[Parameter(Mandatory=$true)][string]$Test,
[Parameter(Mandatory=$false)][hashtable]$Args = @{},
[Parameter(Mandatory=$false)][string]$TestProperty,
[Parameter(Mandatory=$false)][int]$Tries = 5,
[Parameter(Mandatory=$false)][int]$SecondsDelay = 2,
[Parameter(Mandatory=$false)][switch]$ExpectNull
)
$TryCount = 0
$Completed = $false
$MsgFailed = "Command [{0}] failed" -f $Test
$MsgSucceeded = "Command [{0}] succeeded." -f $Test
while (-not $Completed)
{
try
{
$Result = & $Test @Args
$TestResult = if ($TestProperty) { $Result.$TestProperty } else { $Result }
if (-not $TestResult -and -not $ExpectNull)
{
throw $MsgFailed
}
else
{
Write-Verbose $MsgSucceeded
Write-Output $TestResult
$Completed = $true
}
}
catch
{
$TryCount++
if ($TryCount -ge $Tries)
{
$Completed = $true
Write-Output $null
Write-Warning ($PSItem | Select -Property * | Out-String)
Write-Warning ("Command [{0}] failed the maximum number of {1} time(s)." -f $Test, $Tries)
$PSCmdlet.ThrowTerminatingError($PSItem)
}
else
{
$Msg = $PSItem.ToString()
if ($Msg -ne $MsgFailed) { Write-Warning $Msg }
Write-Warning ("Command [{0}] failed. Retrying in {1} second(s)." -f $Test, $SecondsDelay)
Start-Sleep $SecondsDelay
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment