forked from dotnet/dotnet-docker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInvoke-WithRetry.ps1
38 lines (32 loc) · 884 Bytes
/
Invoke-WithRetry.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
#!/usr/bin/env pwsh
# Executes a command and retries if it fails.
[cmdletbinding()]
param (
[Parameter(Mandatory = $true)][string]$Cmd,
[int]$Retries = 2,
[int]$WaitFactor = 6
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$count = 0
$completed = $false
Write-Output "Executing '$Cmd'"
while (-not $completed) {
Invoke-Expression $Cmd
$exit = $LASTEXITCODE
$count++
if ($exit -eq 0) {
$completed = $true
}
else {
if ($count -lt $Retries) {
$wait = [Math]::Pow($WaitFactor, $count - 1)
Write-Output "Retry $count/$Retries exited $exit, retrying in $wait seconds..."
Start-Sleep $wait
}
else {
Write-Output "Retry $count/$Retries exited $exit, no more retries left."
throw "Failed to execute '$Cmd'"
}
}
}