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;
No comments:
Post a Comment