How to retry commands in PowerShell

by Richard Kerslake

Recently while working on a set of scripts to provision some infrastructure in Azure, I needed to be able to retry various commands in case of intermittent failures. With remote infrastructure in particular it is worth considering retry logic, because you never know when you might have trouble reaching it, or internal problems in the remote data centre.

I was also parallelising some tasks using PowerShell background jobs. Each job at some point needed to access a configuration file. However without the ability to retry accessing the file, errors were occasionally being seen due to the file being locked by another process.

Having suitable retry logic can result in a much more robust application (or set of scripts)!

What I needed was a PowerShell equivalent to the Endjin.Retry framework.

After a little searching, I realised I’d have to implement the retry logic myself. As very similar retry behaviour ended up being used in multiple places, it was pulled out into a separate function, called Retry-Command:

Example usage of Retry-Command:

Verbose output for a failed Get-Process command that has retried the default number of times:

Verbose output for a successful Get-Process command:

And there we have it!

I am aware that PowerShell Workflows allow retrying of activities, but didn’t want to get into workflows for this particular requirement. I might write a future post on workflows and the retry mechanism available there. Let me know if that would be interesting for you and I haven’t gotten round to it yet!

P.S. Did you enjoy this post on PowerShell? Follow me on Twitter!

@kerslakerichard