Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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