Functions/Instances/Watch-CdsOperation.ps1

<#
    .SYNOPSIS
    Monitor operation completion.
#>

function Watch-CdsOperation {
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory, ValueFromPipeline)]
        [Guid]
        $OperationId
    )
    begin {   
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew(); 
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters); 
        Assert-CdsIsAdmin;
    }    
    process {
        
        $credentials = $Global:CdsContext.Credentials;
        $apiUrl = $Global:CdsContext.AdminApiUrl;

        $operation = Get-CrmOperationStatus -ApiUrl $apiUrl -Credential $credentials -Id $OperationId;
        while($operation.Status -eq "Running")
        {
            Start-Sleep -Seconds 10;
            $operation = Get-CrmOperationStatus -ApiUrl $apiUrl -Credential $credentials -Id $OperationId;
            $stageData = $operation.Information[2].Description | ConvertFrom-Json;
            Write-HostAndLog -Message "Checking operation $OperationId status => $($operation.Status)";
        }  

    }
    end {
        $StopWatch.Stop();
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }    
}

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