functions/common/Invoke-WithRetry.ps1

function Invoke-WithRetry {
    param(
        [scriptblock]$ScriptBlock,
        [int]$MaxRetries = 5,
        [int]$RetryDelaySeconds = 60,
        [string]$LogFile = $null,
        [string]$CommandText = $null
    )

    $attempt = 0
    while ($attempt -lt $MaxRetries) {
        try {
            $attempt++

            if ($LogFile) {
                Invoke-LoggedTask $ScriptBlock $LogFile $CommandText
            } else {
                & $ScriptBlock
            }

            return
        }
        catch {
            Write-LogLine -Message "Fehler beim Versuch $attempt : $_" -LogFilePath $LogFile
            if ($attempt -lt $MaxRetries) {
                Write-LogLine -Message "Warte $RetryDelaySeconds Sekunden vor erneutem Versuch..." -LogFilePath $LogFile
                Start-Sleep -Seconds $RetryDelaySeconds
            }
            else {
                Write-LogLine -Message "Maximale Anzahl an Versuchen ($MaxRetries) erreicht. Task fehlgeschlagen." -LogFilePath $LogFile
                throw
            }
        }
    }
}