-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathInvoke-ScriptWithRetry.ps1
More file actions
48 lines (48 loc) · 1.33 KB
/
Invoke-ScriptWithRetry.ps1
File metadata and controls
48 lines (48 loc) · 1.33 KB
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
param(
[Parameter(Mandatory = $true)]
[scriptblock]$ScriptBlock,
[Parameter(Mandatory = $false)]
[scriptblock]$RetryScriptBlock,
[Parameter(Mandatory = $false)]
[int]$MaxAttempts = 3,
[Parameter(Mandatory = $false)]
[int]$SleepIntervalSeconds = 30
)
begin {
$count = 0
}
process {
do {
$count++
try {
if ($count -gt 1) {
# retry
if ($RetryScriptBlock) {
Write-Host "Invoking retry script block (attempt $count/$MaxAttempts):"
Write-Host $RetryScriptBlock
$RetryScriptBlock.Invoke()
return
} else {
Write-Host "Retrying invocation of script block (attempt $count/$MaxAttempts):"
Write-Host $ScriptBlock
$ScriptBlock.Invoke()
return
}
}
# initial
Write-Host "Running script block (attempt $count/$MaxAttempts):"
Write-Host $ScriptBlock
$ScriptBlock.Invoke()
return
}
catch {
Write-Host "Error attempting to run script block!" -ForegroundColor Red
Write-Host $_.Exception -ForegroundColor Red
if ($count -lt $MaxAttempts) {
Write-Host "Waiting $SleepIntervalSeconds second(s) before retrying..."
Start-Sleep -Seconds $SleepIntervalSeconds
}
}
} while ($count -lt $MaxAttempts)
throw "Maximum attempts exhausted. ($MaxAttempts)"
}