Created
February 6, 2018 18:39
-
-
Save YakDriver/a28d6a9e17507068384afd562ae26941 to your computer and use it in GitHub Desktop.
Retry-TestCommand
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-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