Skip to content

Instantly share code, notes, and snippets.

@dennisroche
Last active August 29, 2015 14:05
Show Gist options
  • Save dennisroche/efd031ef01da4f8bce46 to your computer and use it in GitHub Desktop.
Save dennisroche/efd031ef01da4f8bce46 to your computer and use it in GitHub Desktop.
Retry Powershell Cmdlet

Usage, waiting for a resource. It will attempt to retry 3 times, with a 5 second delay between each.

Retry -Attemps 3 -Delay 5 {        
    if (-not (Test-Path "$($volume.DriveLetter):\Windows\System32\config")) {
        Throw "The VHDx mounted at $($volume.DriveLetter):\ is not a Windows System volume."
    }
}
function Retry {
[CmdletBinding()]
param (
[Parameter(Mandatory=$false)]
[Alias("Attemps")]
[int]$maxAttempts = 3,
[Parameter(Mandatory=$false)]
[Alias("Delay")]
[int]$secondsBeforeRetrying = 5,
[Parameter(Mandatory=$true)]
[ScriptBlock]$script
)
$attempts = 0
do {
try {
&$script
} catch {
$attempts = $attempts + 1
if ($attempts -gt $maxAttempts){
Throw
}
Start-Sleep -Seconds $secondsBeforeRetrying
}
} while ($true)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment