Skip to content

Instantly share code, notes, and snippets.

@joerodgers
Last active February 9, 2018 18:02
Show Gist options
  • Save joerodgers/13fdad03ecd26f5ae90e35b2055a1930 to your computer and use it in GitHub Desktop.
Save joerodgers/13fdad03ecd26f5ae90e35b2055a1930 to your computer and use it in GitHub Desktop.
Invoke-ClientContextWithRetry.ps1 - Executes a client context query, with logic to handle service throttling and other transient errors.
function Invoke-ClientContextWithRetry
{
[cmdletbinding()]
param
(
[parameter(Mandatory=$true)][Microsoft.SharePoint.Client.ClientContext]$ClientContext,
[parameter(Mandatory=$false)][int]$Delay = 10,
[parameter(Mandatory=$false)][int]$RetryAttempts = 5
)
begin
{
$executions = 1
}
process
{
do
{
try
{
$ClientContext.ExecuteQuery()
return
}
catch [System.Net.WebException]
{
$response = $_.Exception.Response -as [System.Net.HttpWebResponse]
$statusCode = [int]$response.StatusCode
Write-Verbose "Full Exception Details: $($_.Exception)"
Write-Verbose "Status Code: $statusCode"
# 429 and 503 are throttling exceptions
if( $response -and ($statusCode -eq 429 -or $statusCode -eq 503) )
{
Write-Warning -Message "Execution attempt $executions was throttled, trying again in $Delay seconds."
$executions++
Start-Sleep -Seconds $Delay
}
# seeing erroneous 403 exceptions that require a retry
elseif( $response -and $statusCode -eq 403 )
{
Write-Warning -Message "Execution attempt $executions was forbidden, trying again in $Delay seconds."
$executions++
Start-Sleep -Seconds $Delay
}
elseif( $response -and $statusCode -eq 404 )
{
Write-Warning -Message "A site with the URL $($ClientContext.Url) was not found in the tenant."
return
}
else
{
Write-Error -Message "An error occurred connecting to $($ClientContext.Url). Exception: $($_.Exception.Message)"
return
}
}
catch
{
Write-Verbose "Full Exception Details: $($_.Exception)"
if( $_.Exception.Message -match "Access to this Web site has been blocked")
{
Write-Warning -Message "Cannot contact site at the specified URL $ContextUrl. Access to this Web site has been blocked."
return
}
Write-Error -Message "Unexpected execution exception: $($_.Exception.Message)"
}
}
while( $executions -le $RetryAttempts )
Write-Error -Message "$($MyInvocation.MyCommand.Name) - Exceeded retry threshold for context URL: $($ClientContext.Url)"
}
end
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment