src/Administration/Copy-XrmInstance.ps1

<#
    .SYNOPSIS
    Copy instance to another.

    .DESCRIPTION
    Copy given source instance to target source instance, wait for the copy to end and return its result.
    A refused request, a failed copy, or a copy not ended after TimeoutInMinutes raises an error (before 2.0.0.81 a failed copy was announced as ended).

    .PARAMETER SourceInstanceDomainName
    Instance domain name (myinstance => myinstance.crm.dynamics1.com) that you want to copy

    .PARAMETER TargetInstanceDomainName
    Instance domain name (myinstance => myinstance.crm.dynamics1.com) that you want to overwrite

    .PARAMETER CopyType
    Copy type : MinimalCopy (schema only) / FullCopy (All)

    .PARAMETER TimeoutInMinutes
    Maximum time to wait for the copy to end. (Default: 1440, one day)

    .OUTPUTS
    PSCustomObject. Result of the operation (see Watch-XrmOperation): OperationUrl, Type, State, Stages, Succeeded, Message. The progress is also written to the host and to the log.

    .EXAMPLE
    Connect-XrmAdmin -TenantId $tenantId -ApplicationId $applicationId -ClientSecret $clientSecret;
    $result = Copy-XrmInstance -SourceInstanceDomainName "contoso-prod" -TargetInstanceDomainName "contoso-uat" -CopyType MinimalCopy -TimeoutInMinutes 240;

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

function Copy-XrmInstance {
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Medium")]
    [OutputType([PSCustomObject])]
    param
    (
        [Parameter(Mandatory, ValueFromPipeline)]
        [String]
        $SourceInstanceDomainName,

        [Parameter(Mandatory = $true)]
        [String]
        $TargetInstanceDomainName,

        [Parameter(Mandatory = $true)]
        [ValidateSet("FullCopy", "MinimalCopy")]
        [String]
        $CopyType,

        [Parameter(Mandatory = $false)]
        [ValidateRange(1, 10080)]
        [int]
        $TimeoutInMinutes = 1440
    )
    begin {   
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew(); 
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters); 
        Assert-XrmAdminConnected;
    }    
    process {    
        $sourceInstance = Get-XrmInstance -Name $SourceInstanceDomainName;
        $targetInstance = Get-XrmInstance -Name $TargetInstanceDomainName;

        $copyToRequest = [pscustomobject]@{
            SourceEnvironmentId   = $sourceInstance.Id
            TargetEnvironmentName = $targetInstance.DisplayName
            CopyType              = $CopyType
        }

        if (-not $PSCmdlet.ShouldProcess($targetInstance.Id, "Overwrite environment with a copy")) { return; }
        $response = Copy-PowerAppEnvironment -EnvironmentName $targetInstance.Id -CopyToRequestDefinition $copyToRequest;
        # The copy is watched until it ends, and a failure raises an error (H22: it was announced as ended)
        $operation = "Copy of environment '$SourceInstanceDomainName' to '$TargetInstanceDomainName'";
        $operationStatusUrl = Assert-XrmAdminResponseInternal -Response $response -Operation $operation;
        if (-not $operationStatusUrl) {
            throw "$operation accepted without an operation to watch (HTTP $($response.Code)).";
        }
        try {
            Watch-XrmOperation -OperationUrl $operationStatusUrl -TimeoutInMinutes $TimeoutInMinutes -ThrowOnFailure;
        }
        catch {
            throw [System.InvalidOperationException]::new("$operation failed: $($_.Exception.Message)", $_.Exception);
        }
    }
    end {
        $StopWatch.Stop();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }    
}

Export-ModuleMember -Function Copy-XrmInstance -Alias *;