-
Notifications
You must be signed in to change notification settings - Fork 4
/
Execute-With-Retry.ps1
executable file
·63 lines (55 loc) · 1.94 KB
/
Execute-With-Retry.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<#
https://gist.github.com/alexbevi/34b700ff7c7c53c7780b
This function can be used to pass a ScriptBlock (closure) to be executed and returned.
The operation retried a few times on failure, and if the maximum threshold is surpassed, the operation fails completely.
Params:
Command - The ScriptBlock to be executed
RetryDelay - Number (in seconds) to wait between retries
(default: 5)
MaxRetries - Number of times to retry before accepting failure
(default: 3)
VerboseOutput - More info about internal processing
(default: false)
Examples:
Execute-With-Retry { $connection.Open() }
$result = Execute-With-Retry -RetryDelay 1 -MaxRetries 2 { $command.ExecuteReader() }
#>
function Execute-With-Retry {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline,Mandatory)]
$Command,
$RetryDelay = 5,
$MaxRetries = 3,
$VerboseOutput = $false
)
$currentRetry = 0
$success = $false
$cmd = $Command.ToString()
do {
try
{
$result = & $Command
$success = $true
if ($VerboseOutput -eq $true) {
$Host.UI.WriteDebugLine("Successfully executed [$cmd]")
}
return $result
}
catch [System.Exception]
{
$currentRetry = $currentRetry + 1
if ($VerboseOutput -eq $true) {
$Host.UI.WriteErrorLine("Failed to execute [$cmd]: " + $_.Exception.Message)
}
if ($currentRetry -gt $MaxRetries) {
throw "Could not execute [$cmd]. The error: " + $_.Exception.ToString()
} else {
if ($VerboseOutput -eq $true) {
$Host.UI.WriteDebugLine("Waiting $RetryDelay second(s) before attempt #$currentRetry of [$cmd]")
}
Start-Sleep -s $RetryDelay
}
}
} while (!$success);
}