Blog Stats
  • Posts - 148
  • Articles - 0
  • Comments - 92
  • Trackbacks - 14

 

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 retries: $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;  

Comments have been closed on this topic.
 

 

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
Copyright © Pawel Pabich