Created
October 20, 2025 12:33
-
-
Save santisq/e494d5f01e0c7b811a68fe5c52646dd6 to your computer and use it in GitHub Desktop.
simple retry function
This file contains hidden or 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-Retry { | |
| [Alias('retry')] | |
| [CmdletBinding()] | |
| param( | |
| [Parameter(Mandatory)] | |
| [scriptblock] $Scriptblock, | |
| [Parameter()] | |
| [scriptblock] $RetryHandler, | |
| [Parameter()] | |
| [ValidateNotNull()] | |
| [int] $RetryCount = 5, | |
| [Parameter()] | |
| [switch] $UseLocalScope | |
| ) | |
| $ErrorActionPreference = 'Stop' | |
| while ($retryCount--) { | |
| try { | |
| if ($UseLocalScope) { | |
| return . $Scriptblock | |
| } | |
| return & $scriptblock | |
| } | |
| catch { | |
| $previousError = $_ | |
| if (-not $RetryHandler) { | |
| continue | |
| } | |
| if ($UseLocalScope) { | |
| . $retryHandler $_ | |
| continue | |
| } | |
| & $retryHandler $_ | |
| } | |
| } | |
| if ($previousError) { | |
| $PSCmdlet.ThrowTerminatingError($previousError) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment