Networking.psm1
<#
.SYNOPSIS This function invokes a REST method call repeatedly if an error or failed call occurs. #> function Invoke-RestMethodWithRetry { param ( # The Uniform Resource Identifier (URI) of the Internet resource to which the # web request is sent. [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$uri, # The headers of the web request. [Parameter(Mandatory=$false)] [ValidateNotNull()] $headers, # The body of the web request. [Parameter(Mandatory=$false)] [ValidateNotNull()] $body, # The method of the web request. [Parameter(Mandatory=$true)] [ValidateSet("Default", "Delete", "Get", "Head", "Merge", "Options", "Patch", "Post", "Put", "Trace")] [String]$method, # The interval in milliseconds to wait to repeat the request. [Parameter(Mandatory=$true)] [ValidateNotNull()] [Int]$intervalMilliseconds, # The number of requests to make before declaring that the call has failed. [Parameter(Mandatory=$true)] [ValidateNotNull()] [Int]$maximumNumberOfCalls, # Select whether to return an unsuccessful response object. [Parameter(Mandatory=$false)] [Switch]$returnUnsuccessfulResponseObject ) # Create hash table with params $invokeRestMethodParams = @{ Uri = $uri Method = $method } if (![String]::IsNullOrWhiteSpace($headers)) { $invokeRestMethodParams.Add("Headers", $headers) } if (![String]::IsNullOrWhiteSpace($body)) { $invokeRestMethodParams.Add("Body", $body) } # Keep track of last exception message (if any) $lastExceptionMessage = "" # Try to call repeatedly for ($i = 0; $i -lt $maximumNumberOfCalls; ++$i) { # Try to call try { $response = Invoke-RestMethod @invokeRestMethodParams if ($response.Result -eq "Success") { return $response } } catch { # Save exception message $lastExceptionMessage = $_.Exception.Message } # Wait for the next call Start-Sleep -Milliseconds $intervalMilliseconds } # Output last exception message if any if (![String]::IsNullOrWhiteSpace($lastExceptionMessage)) { Write-Error "Exception when invoking REST call. `r`n$($lastExceptionMessage)" } # Output error message in response if any else { Write-Error "REST call failed with error code $($response.ErrorCode) and error message '$($response.ErrorMessage)'." if ($returnUnsuccessfulResponseObject) { return $response } } } |