Block Retry using Powershell
I’ve been doing a lot of Powershell scripting lately, and one of the features I’ve really been pining for is the ability to apply some form of retry logic to either a function or a block.
Take the following sample:
1
2
3
4
5
6
7
8
function RandomlyFail
{
$rnd = Get-Random -minimum 1 -maximum 3
if ($rnd -eq 2) {
throw "OH NOES!!!"
}
$Host.UI.WriteLine("W00t!!!")
}
Depending on what the random number we get is, we’ll get one of two scenarios:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Success
RandomlyFail
W00t!!!
# Failure
RandomlyFail
OH NOES!!!
At line:62 char:9
+ throw "OH NOES!!!"
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (OH NOES!!!:String) [], RuntimeException
+ FullyQualifiedErrorId : OH NOES!!!
Now, if this happened to be part of a larger script and we didn’t have everything wrapped in a try..catch
block, execution could potentially stop there.
Since Powershell supports closures, we can write a function that accepts a script block as a parameter.
Now, if we retrofit our sample above:
1
Execute-With-Retry -RetryDelay 1 -VerboseOutput $true { RandomlyFail }
1
2
3
4
5
6
7
8
9
10
Failed to execute [ RandomlyFail ]: OH NOES!!!
DEBUG: Waiting 1 second(s) before attempt #1 of [ RandomlyFail ]
Failed to execute [ RandomlyFail ]: OH NOES!!!
DEBUG: Waiting 1 second(s) before attempt #2 of [ RandomlyFail ]
Failed to execute [ RandomlyFail ]: OH NOES!!!
DEBUG: Waiting 1 second(s) before attempt #3 of [ RandomlyFail ]
Failed to execute [ RandomlyFail ]: OH NOES!!!
DEBUG: Waiting 1 second(s) before attempt #4 of [ RandomlyFail ]
W00t!!!
DEBUG: Successfully executed [ RandomlyFail ]
The inspiration for this comes from an excellent article by Pawel Pabich.
This post is licensed under CC BY 4.0 by the author.
Comments powered by Disqus.