src/Administration/Restore-XrmInstance.ps1

<#
    .SYNOPSIS
    Restore instance at given time.

    .DESCRIPTION
    Restore a backup of given instance to itself or another instance.
    Give either BackupLabel (a labelled backup, see Get-XrmBackup) or RestoreTimeUtc (a point in time); without them, use Copy-XrmInstance.
    Wait for the restore to end and return its result. A refused request, a failed restore, or a restore not ended after TimeoutInMinutes raises an error
    (before 2.0.0.81 an accepted restore raised an empty error, and a failed one was announced as ended).

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

    .PARAMETER TargetInstanceDomainName
    Instance domain name (myinstance => myinstance.crm.dynamics1.com) where you want to restore. (Default: the source instance)

    .PARAMETER TargetInstanceNewDisplayName
    Display name given to the target instance after the restore. (Default: the current display name of the target instance)

    .PARAMETER TargetInstanceSecurityGroupId
    AAD Security Group ID to define on target instance to restrict users access

    .PARAMETER RestoreTimeUtc
    Date time in UTC of restore point

    .PARAMETER BackupLabel
    Name of the backup

    .PARAMETER TimeoutInMinutes
    Maximum time to wait for the restore 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 = Restore-XrmInstance -SourceInstanceDomainName "contoso-prod" -TargetInstanceDomainName "contoso-uat" -BackupLabel "Before release 2.4";

    .EXAMPLE
    Restore-XrmInstance -SourceInstanceDomainName "contoso-prod" -TargetInstanceDomainName "contoso-uat" -RestoreTimeUtc ([DateTime]::UtcNow.AddHours(-2)) -TargetInstanceNewDisplayName "Contoso UAT (restored)";

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

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

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [String]
        $TargetInstanceDomainName,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [String]
        $TargetInstanceNewDisplayName,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [Guid]
        $TargetInstanceSecurityGroupId,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [DateTime]
        $RestoreTimeUtc,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]
        $BackupLabel,

        [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 {

        $restoreTimeUtcValue = "";
        if ($PSBoundParameters.BackupLabel) {
            $backup = Get-XrmBackup -InstanceDomainName $SourceInstanceDomainName -BackupLabel $BackupLabel;
            if (-not $backup) {
                throw "No backup found for label '$BackupLabel'";
            }
            $restoreTimeUtcValue = $backup.backupPointDateTime;
        }
        else {
            if (-not $PSBoundParameters.RestoreTimeUtc) {
                throw "Must use Copy-XrmInstance instead of Restore-XrmInstance!";
            }
            $restoreTimeUtcValue = $RestoreTimeUtc.ToString("yyyy-MM-dd HH:mm:ss");
        }

        $sourceInstance = Get-XrmInstance -Name $SourceInstanceDomainName;
        $restoreRequest = [pscustomobject]@{
            SourceEnvironmentId  = $sourceInstance.Id;
            RestorePointDateTime = $restoreTimeUtcValue
        }

        if ($PSBoundParameters.TargetInstanceDomainName) {
            $targetInstance = Get-XrmInstance -Name $TargetInstanceDomainName;
        }
        else {
            $targetInstance = $sourceInstance;
        }

        if ($PSBoundParameters.TargetInstanceNewDisplayName) {
            $restoreRequest | Add-Member -MemberType NoteProperty -Name "TargetEnvironmentName" -Value $TargetInstanceNewDisplayName;
        }
        else {
            $restoreRequest | Add-Member -MemberType NoteProperty -Name "TargetEnvironmentName" -Value $targetInstance.DisplayName;
        }

        if ($PSBoundParameters.TargetInstanceSecurityGroupId) {
            $restoreRequest | Add-Member -MemberType NoteProperty -Name "TargetSecurityGroupId" -Value $TargetInstanceSecurityGroupId;
        }

        if (-not $PSCmdlet.ShouldProcess($targetInstance.Id, "Overwrite environment with a backup")) { return; }
        $response = Restore-PowerAppEnvironment -EnvironmentName $targetInstance.Id -RestoreToRequestDefinition $restoreRequest -WaitUntilFinished $false;
        # 202 (Accepted) is the normal answer: "if ($response.Code) { throw }" raised an empty error on it (H28), and a failed restore was announced as ended (H22)
        $operation = "Restore of environment '$SourceInstanceDomainName' to '$($targetInstance.Name)'";
        $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 Restore-XrmInstance -Alias *;