Created
July 28, 2022 17:57
-
-
Save JKerens/a77a4cd61585e400a5f9662f49c74b77 to your computer and use it in GitHub Desktop.
PowerShell Retry Wrapper
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 WithRetry { | |
| param ( | |
| [Parameter(Mandatory = $true, ValueFromPipeline = $true)] | |
| [ValidateNotNull()] | |
| [ScriptBlock] $Command, | |
| [Parameter(Mandatory = $false)] | |
| [int]$RetryCount = 3 | |
| ) | |
| Write-Host "Retry Injection Scope" | |
| $i = 0 | |
| do { | |
| try { | |
| return Invoke-Command $Command | |
| } | |
| catch { | |
| Write-Host "Retry #$((++$i))" -fore Red | |
| } | |
| } until ($i -ge $RetryCount) | |
| } | |
| function Invoke-FlakyCommand { | |
| param ( | |
| [Parameter(Mandatory = $true, ValueFromPipeline = $true)] | |
| [int]$Number | |
| ) | |
| # Retries the command on transient errors. | |
| WithRetry { | |
| if (Get-Random -InputObject $true, $false) { | |
| throw "Oooops" | |
| } | |
| return $Number | |
| } | |
| } | |
| (1..5) | ForEach-Object { $_ | Invoke-FlakyCommand } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment