PowerShell Retry-Command

Apparently there is no native Powershell command to retry a CmdLet. I found a few examples online but thought I'd try my own.

function Retry-Command {

    Param([String] $CommandName,
          [hashtable] $CommandArgs = @{},
          [int] $MaxRetries=3,
          [int] $SleepSeconds=2 )

    $retrycount = 0
    $CommandArgs.ErrorAction='Stop'
    while ($retrycount++ -lt $MaxRetries) {

        try {

            &$CommandName @CommandArgs
            return
        }
        catch {

            Write-Error -ErrorRecord $_
            Start-Sleep -Seconds $SleepSeconds
        }
    }
    throw "Max retries reached"
}

The only required parameter is the first one which is the command name (the others have default values.) If the command to be retried requires arguments, the caller needs to create a hashtable to pass as the second argument.

By default it will try 3 times in case of error and sleep for 2 seconds before retrying. It automatically adds ErrorAction=Stop to the command's arguments so that the try mechanism works properly and the caller doesn't have to worry about it. This may not work for all commands but most should. As an aside I've seen come CmdLets exhibit strange behavior with ErrorAction=Stop.

I've been testing on Powershell 5 mostly so your mileage may vary.

Example usage with built-in CmdLet Rename-Item

            $rename_item_params = @{
                Path = '\path\for\rename-item';
                NewName = "second-rename-item-argument";
            }
            
            Retry-Command Rename-Item $rename_item_params