Powershell: Simple retry logic

Powershell Header

I am working at some larger powershell scripts right now and so I needed to create a simple retry logic for sending web request to a server.

Powershell retry loop

# Comment
$Stoploop = $false
[int]$Retrycount = "0"

do {
	try {
		Scripts Commands here
		Write-Host "Job completed"
		$Stoploop = $true
		}
	catch {
		if ($Retrycount -gt 3){
			Write-Host "Could not send Information after 3 retrys."
			$Stoploop = $true
		}
		else {
			Write-Host "Could not send Information retrying in 30 seconds..."
			Start-Sleep -Seconds 30
			$Retrycount = $Retrycount + 1
		}
	}
}
While ($Stoploop -eq $false)

Related Posts:

3 thoughts on “Powershell: Simple retry logic

  1. I believe the condition in the while loop should be: $Stoploop -eq $false or it will only “retry” when the commands successfully execute.

  2. Thanks, this helped me out!

    FYI… if you use this with a “copy-item” or “move -item” as your script command, you will run into a non-terminating error condition, as I did. in this case add an:

    $ErrorActionPreference = “Stop”

    above the command to resolve this.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>