Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.