src/Solutions/Watch-XrmCurrentSolutionImport.ps1

<#
    .SYNOPSIS
    Monitor current solution import.

    .DESCRIPTION
    Poll a solution import job (the latest started one by default) until it completes, display its progress and return its result.
    The result is read in the job data: Status is its succeeded attribute (success, warning or failure); a failure, or a component that failed, makes the import failed,
    with the error text of the first failed component as message.
    A job not completed after TimeoutInMinutes raises an error.

    .PARAMETER XrmClient
    Xrm connector initialized to target instance. Use latest one by default. (Dataverse ServiceClient)

    .PARAMETER ImportJobId
    Import job unique identifier, e.g. the ImportJobId given to ImportSolution. (Default: the latest started import job)

    .PARAMETER PollingIntervalSeconds
    Delay between each status check. (Default: 5)

    .PARAMETER TimeoutInMinutes
    Maximum time to wait for the job to complete. (Default: 60)

    .PARAMETER ThrowOnFailure
    Raise an error when the import fails, with its message.

    .OUTPUTS
    PSCustomObject. ImportJobId, SolutionName, Progress, Status, Succeeded, Message. The progress is also displayed in the host.

    .EXAMPLE
    $result = Watch-XrmCurrentSolutionImport -XrmClient $xrmClient -TimeoutInMinutes 30 -ThrowOnFailure;

    .LINK
    https://github.com/AymericM78/PowerDataOps/blob/main/documentation/commands/Watch-XrmCurrentSolutionImport.md
#>

function Watch-XrmCurrentSolutionImport {
    [CmdletBinding()]
    [OutputType([PSCustomObject])]
    param
    (
        [Parameter(Mandatory = $false, ValueFromPipeline)]
        [Microsoft.PowerPlatform.Dataverse.Client.ServiceClient]
        $XrmClient = $Global:XrmClient,

        [Parameter(Mandatory = $false)]
        [Guid]
        $ImportJobId,

        [Parameter(Mandatory = $false)]
        [ValidateRange(1, 600)]
        [int]
        $PollingIntervalSeconds = 5,

        [Parameter(Mandatory = $false)]
        [ValidateRange(1, 1440)]
        [int]
        $TimeoutInMinutes = 60,

        [Parameter(Mandatory = $false)]
        [switch]
        $ThrowOnFailure
    )
    begin {
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters);
    }
    process {
        if (-not $PSBoundParameters.ContainsKey('ImportJobId')) {
            $queryImportJobs = New-XrmQueryExpression -LogicalName "importjob" -TopCount 1;
            $queryImportJobs = $queryImportJobs | Add-XrmQueryOrder -Field "startedon" -OrderType Descending;
            $importJob = Get-XrmMultipleRecords -XrmClient $XrmClient -Query $queryImportJobs | Select-Object -First 1;
            if (-not $importJob) {
                Write-HostAndLog -Message "Import job not found" -Level WARN;
                return;
            }
            $ImportJobId = $importJob.Id;
        }

        # Polled with a pause and a timeout: it was a tight loop without end when the job never completed (H19)
        $startedAt = Get-Date;
        $lastProgress = $null;
        while ($true) {
            # The job row can be missing for a few seconds after ImportSolution starts
            $importJob = $XrmClient | Get-XrmRecord -LogicalName "importjob" -Id $ImportJobId -Columns "solutionname", "completedon", "data", "progress" -AsEntity -IfExists;
            if ($importJob) {
                $progress = [double]$importJob["progress"];
                $solutionName = [string]$importJob["solutionname"];
                if ($progress -ne $lastProgress) {
                    Write-HostAndLog " > $solutionName import in progress... ($progress %)" -ForegroundColor Cyan;
                    Write-Progress -Activity $($MyInvocation.MyCommand.Name) -Status "Importing solution $solutionName... ($progress %)" -PercentComplete ([Math]::Min(100, [Math]::Max(0, $progress))) -Id 1053;
                    $lastProgress = $progress;
                }
                if ($importJob["completedon"]) {
                    break;
                }
            }
            if (((Get-Date) - $startedAt).TotalMinutes -ge $TimeoutInMinutes) {
                Write-Progress -Activity $($MyInvocation.MyCommand.Name) -Id 1053 -Completed;
                throw "Import job '$ImportJobId' not completed after $TimeoutInMinutes minutes.";
            }
            Start-Sleep -Seconds $PollingIntervalSeconds;
        }
        Write-Progress -Activity $($MyInvocation.MyCommand.Name) -Id 1053 -Completed;

        # The import result is in the job data: a failed import also completes (it was shown as "completed")
        # <importexportxml ... errorcode="0" succeeded="success|warning|failure">, then one <result result="..." errorcode errortext /> per component
        $message = $null;
        $status = $null;
        $data = [string]$importJob["data"];
        if (-not [string]::IsNullOrWhiteSpace($data)) {
            try {
                [xml]$dataXml = $data;
                $status = $dataXml.DocumentElement.GetAttribute("succeeded");
                $failure = $dataXml.SelectSingleNode("//result[@result='failure']");
                if ($failure) {
                    $message = $failure.GetAttribute("errortext");
                    if ([string]::IsNullOrWhiteSpace($message)) {
                        $message = "Import failed (error code $($failure.GetAttribute("errorcode"))).";
                    }
                    $status = "failure";
                }
                elseif ($status -eq "failure") {
                    $message = "Import failed (error code $($dataXml.DocumentElement.GetAttribute("errorcode"))).";
                }
            }
            catch {
                Write-HostAndLog -Message "Import job '$ImportJobId': data not readable ($($_.Exception.Message))" -Level WARN;
            }
        }
        $succeeded = ($null -eq $message);
        if ($succeeded) {
            Write-HostAndLog " > $solutionName import completed!" -ForegroundColor Green;
        }
        else {
            Write-HostAndLog " > $solutionName import failed: $message" -ForegroundColor Red;
            if ($ThrowOnFailure) {
                throw "Import of solution '$solutionName' failed (import job '$ImportJobId'): $message";
            }
        }

        [PSCustomObject]@{
            ImportJobId  = $ImportJobId;
            SolutionName = $solutionName;
            Progress     = $progress;
            Status       = $status;
            Succeeded    = $succeeded;
            Message      = $message;
        };
    }
    end {
        $StopWatch.Stop();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }
}

Export-ModuleMember -Function Watch-XrmCurrentSolutionImport -Alias *;