Monday 28 June 2010

Sunday 20 June 2010

Generic retry logic in PowerShell

I spent recently a bit of time writing PowerShell scripts that deploy a system that I’m working on both locally and to QA. Basically, you get the latest code from TFS, run single PowerShell script and press F5 :). Why? Have a look at The Joel Test.
Anyway, while writing those scripts I needed to implement a basic retry logic in multiple places. It turned out that PowerShell supports closures and that you can pass any part of the script to a function as an argument. Having all of that at my disposal made my task very easy:

function Execute-Command($Command, $CommandName) {
$currentRetry = 0;
$success = $false;
do {
try
{
& $Command;
$success = $true;
Log-Debug "Successfully executed [$CommandName] command. Number of entries: $currentRetry";
}
catch [System.Exception]
{
$message = 'Exception occurred while trying to execute [$CommandName] command:' + $_.Exception.ToString();
Log-Error $message;
if ($currentRetry -gt 5) {
$message = "Can not execute [$CommandName] command. The error: " + $_.Exception.ToString();
throw $message;
} else {
Log-Debug "Sleeping before $currentRetry retry of [$CommandName] command";
Start-Sleep -s 1;
}
$currentRetry = $currentRetry + 1;
}
} while (!$success);
}


And this is how you can use it:

$command = { Get-ChildItem $Folder -Recurse | Remove-Item -Recurse -Force};  
$commandName = "Delete content of [$Folder]";
Execute-Command -Command $command -CommandName $commandName;

CloudCamp is coming again to Sydney!

This time you need to take half a day off to attend it but I believe it’s well worth your time and I really enjoyed the previous camp.