Created
December 16, 2014 14:18
-
-
Save paulryan/b8502c4030aec27d71fe to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Function ExecuteQueryWithExponentialRetry | |
{ | |
Param ( | |
[Microsoft.SharePoint.Client.ClientContext]$ctx | |
) | |
return ExecuteQueryWithExponentialRetryInternal $ctx 3 1000 | |
} | |
Function ExecuteQueryWithExponentialRetryInternal | |
{ | |
Param ( | |
[Microsoft.SharePoint.Client.ClientContext]$ctx, | |
[int]$retryCount, | |
[int]$delayMs | |
) | |
$retryAttempts = 0 | |
$backoffInterval = $delayMs | |
if ($retryCount -lt 1) | |
{ | |
Throw [System.IO.ArgumentException] "Provide a retry count greater than zero." | |
} | |
if ($delayMs -lt 1) | |
{ | |
Throw [System.IO.ArgumentException] "Provide a delay greater than zero." | |
} | |
while ($retryAttempts -lt $retryCount) | |
{ | |
try | |
{ | |
$result = $ctx.ExecuteQuery() | |
return $result | |
} | |
catch [System.Net.WebException] | |
{ | |
# Check if response was throttled | |
$statusCode = 0 | |
if(($_.Exception -ne $null) -and ($_.Exception.Response -ne $null)) | |
{ | |
$statusCode = [int]([System.Net.HttpWebResponse]$_.Exception.Response).StatusCode | |
} | |
if($statusCode -eq 429) | |
{ | |
Write-Host "" | |
Write-Host "Request throttled, waiting $backoffInterval milliseconds..." -F Yellow -NoNewLine | |
[System.Threading.Thread]::Sleep($backoffInterval) | |
$retryAttempts++ | |
$backoffInterval = $backoffInterval * 2 | |
} | |
else | |
{ | |
# If not throttled then throw | |
Throw $_ | |
} | |
} | |
} | |
Throw "ExecuteQueryWithExponentialRetry, failed to execute query" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment