src/Administration/Watch-XrmOperation.ps1
|
<# .SYNOPSIS Monitor operation completion. .DESCRIPTION Poll an admin operation (environment copy, restore...) from its status URL until it ends, display its state and stages when they change, and return its result. The operation ends in state Succeeded or Completed (success), or Failed, Canceled or Aborted (failure). NotStarted and the other states are waited for. An operation not ended after TimeoutInMinutes, or a status URL that keeps answering an error (10 checks in a row), raises an error. .PARAMETER OperationUrl Operation Url provided when admin operation is invoked. .PARAMETER PollingIntervalSeconds Delay between each status check. (Default: 5) .PARAMETER TimeoutInMinutes Maximum time to wait for the operation to end. (Default: 1440, one day) .PARAMETER ThrowOnFailure Raise an error when the operation fails, with its message. .OUTPUTS PSCustomObject. OperationUrl, Type, State, Stages (Name, State), Succeeded, Message. The state and stages are also written to the host and to the log when they change. .EXAMPLE Connect-XrmAdmin -TenantId $tenantId -ApplicationId $applicationId -ClientSecret $clientSecret; $response = Copy-PowerAppEnvironment -EnvironmentName $targetEnvironmentId -CopyToRequestDefinition $copyRequest; $result = Watch-XrmOperation -OperationUrl $response.Headers["Operation-Location"] -PollingIntervalSeconds 30 -TimeoutInMinutes 240 -ThrowOnFailure; .LINK https://github.com/AymericM78/PowerDataOps/blob/main/documentation/commands/Watch-XrmOperation.md #> function Watch-XrmOperation { [CmdletBinding()] [OutputType([PSCustomObject])] param ( [Parameter(Mandatory, ValueFromPipeline)] [string] $OperationUrl, [Parameter(Mandatory = $false)] [ValidateRange(1, 3600)] [int] $PollingIntervalSeconds = 5, [Parameter(Mandatory = $false)] [ValidateRange(1, 10080)] [int] $TimeoutInMinutes = 1440, [Parameter(Mandatory = $false)] [switch] $ThrowOnFailure ) begin { $StopWatch = [System.Diagnostics.Stopwatch]::StartNew(); Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters); Assert-XrmAdminConnected; } process { # Before 2.0.0.81 the loop ended on any state but Running (NotStarted included), never raised a failure and had no timeout (M42) $startedAt = Get-Date; $lastLine = $null; $lastError = $null; $errorCount = 0; $status = $null; while ($true) { Start-Sleep -Seconds $PollingIntervalSeconds; $operationData = Get-AdminPowerAppOperationStatus -OperationStatusUrl $OperationUrl; $code = if ($operationData -and $operationData.PSObject.Properties["Code"] -and $null -ne $operationData.Code -and "$($operationData.Code)" -ne "") { [int]$operationData.Code } else { $null }; $content = $null; if ($operationData -and $operationData.PSObject.Properties["Internal"] -and $operationData.Internal -and $operationData.Internal.PSObject.Properties["Content"]) { $content = [string]$operationData.Internal.Content; } if ($null -ne $code -and $code -ge 400) { $errorCount++; $lastError = "HTTP $code"; if ($operationData.PSObject.Properties["Error"] -and $operationData.Error) { $lastError += ": $(if ($operationData.Error.PSObject.Properties['message']) { $operationData.Error.message } else { $operationData.Error })"; } # Throttling and server errors are retried until the timeout; other errors 10 times in a row if ($code -ne 429 -and $code -lt 500 -and $errorCount -ge 10) { throw "Operation status '$OperationUrl' not readable: $lastError"; } } else { $errorCount = 0; $status = ConvertFrom-XrmAdminOperationInternal -Content $content; } if ($status) { $stagesText = ($status.Stages | ForEach-Object { "$($_.Name) = $($_.State)" }) -join " | "; $line = "Operation $($status.Type): $($status.State) [$stagesText]"; if ($line -ne $lastLine) { $stateColor = switch ($status.State) { "Running" { "Yellow" } "Succeeded" { "Green" } "Completed" { "Green" } "Failed" { "Red" } default { "Gray" } }; Write-HostAndLog "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') " -NoNewline -ForegroundColor Gray -NoTimeStamp; Write-HostAndLog $line -ForegroundColor $stateColor -NoTimeStamp; $lastLine = $line; } if ($status.IsCompleted) { break; } } if (((Get-Date) - $startedAt).TotalMinutes -ge $TimeoutInMinutes) { $lastState = if ($status) { $status.State } elseif ($lastError) { $lastError } else { "unknown" }; throw "Operation '$OperationUrl' not ended after $TimeoutInMinutes minutes (last state: $lastState)."; } } if (-not $status.Succeeded -and $ThrowOnFailure) { throw $status.Message; } [PSCustomObject]@{ OperationUrl = $OperationUrl; Type = $status.Type; State = $status.State; Stages = $status.Stages; Succeeded = $status.Succeeded; Message = $status.Message; }; } end { $StopWatch.Stop(); Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch; } } Export-ModuleMember -Function Watch-XrmOperation -Alias *; |