Skip to content

Instantly share code, notes, and snippets.

@scolton99
Created April 26, 2024 12:35
Show Gist options
  • Save scolton99/b0c4e5f43e564046eabede4452d3a1c9 to your computer and use it in GitHub Desktop.
Save scolton99/b0c4e5f43e564046eabede4452d3a1c9 to your computer and use it in GitHub Desktop.
Test Transient Error Handling in PowerShell
function Get-RandomSuccess {
$val = Get-Random -Maximum 2
$val -eq 0
}
function Get-RandomThrow {
if (!(Get-RandomSuccess)) {
throw "ERR"
}
}
function Test-Function {
for ($tries = 0; ; ++$tries) {
try {
$ret = Get-RandomThrow
break
} catch {
if ($tries -ge 3) {
throw $_
} else {
Write-Host "Attempt $tries, waiting 1 second"
Start-Sleep -Seconds 1
}
}
}
$ret
}
Test-Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment