Created
March 20, 2023 12:04
-
-
Save egil/59242fb8230741e96877b64430f7f04b to your computer and use it in GitHub Desktop.
A PowerShell helper function that will invoke a script block a number of times until it completes successfully, with a configurable delay between retries.
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 Invoke-With-Retry { | |
[CmdletBinding()] | |
Param( | |
[Parameter(Position = 0, Mandatory = $true)] | |
[scriptblock]$ScriptBlock, | |
[Parameter(Position = 1, Mandatory = $false)] | |
[int]$Retries = 5, | |
[Parameter(Position = 2, Mandatory = $false)] | |
[int]$DelayInMilliseconds = 100 | |
) | |
Begin { | |
$count = 0 | |
} | |
Process { | |
do { | |
$count++ | |
$output = $null | |
try { | |
$output = Invoke-Command -Command $ScriptBlock -ErrorVariable err -ErrorAction Stop | |
if ($err.Count -gt 0) { | |
throw $errors | |
} | |
if ($LastExitCode -gt 0) { | |
throw $output | |
} | |
return $output | |
} | |
catch { | |
# A ScriptTerminatedException is thrown when a PowerShell script is terminated by an | |
# external process or action, such as a user pressing Ctrl+C or a system shutdown. | |
if ($_.Exception.GetType().Name -eq "ScriptTerminatedException") { | |
return | |
} | |
Start-Sleep -Milliseconds $DelayInMilliseconds | |
} | |
} while ($count -lt $Retries) | |
Write-Warning "Failed to execute script block successfully. The maximum number of retries ($Retries) exceeded." | |
return $output | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment