Skip to content
Richard Kerslake By Richard Kerslake Engineer I
How to retry commands in PowerShell

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.

Programming C# 12 Book, by Ian Griffiths, published by O'Reilly Media, is now available to buy.

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:

The Introduction to Rx.NET 2nd Edition (2024) Book, by Ian Griffiths & Lee Campbell, is now available to download for FREE.

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.

Richard Kerslake

Engineer I

Richard Kerslake

Richard has a background in financial services, working on large scale distributed trading systems. Richard has a passion for delivering real business value to endjin’s customers, who are seeking to take advantage of Microsoft Azure and the Cloud.

Richard worked at endjin between 2014-2017.