src/Administration/Backup-XrmInstance.ps1

<#
    .SYNOPSIS
    Backup instance

    .DESCRIPTION
    Add a backup for given instance. A refused request raises an error (before 2.0.0.81 the error details were returned).

    .PARAMETER InstanceDomainName
    Instance domain name (myinstance => myinstance.crm.dynamics1.com)

    .PARAMETER BackupLabel
    Name of the backup

    .PARAMETER BackupDescription
    Backup description

    .OUTPUTS
    PSCustomObject. The new backup, as returned by Backup-PowerAppEnvironment.

    .EXAMPLE
    Connect-XrmAdmin -TenantId $tenantId -ApplicationId $applicationId -ClientSecret $clientSecret;
    $backup = Backup-XrmInstance -InstanceDomainName "contoso-prod" -BackupLabel "Before release 2.4" -BackupDescription "Taken by the release pipeline";

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

function Backup-XrmInstance {
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    [OutputType([PSCustomObject])]
    param
    (
        [Parameter(Mandatory, ValueFromPipeline)]
        [String]
        $InstanceDomainName,

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

        [Parameter(Mandatory = $false)]
        [String]
        $BackupDescription
    )
    begin {   
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew(); 
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters); 
        Assert-XrmAdminConnected;
    }    
    process {    
        $instance = Get-XrmInstance -Name $InstanceDomainName;
        $backupRequest = [pscustomobject]@{
            Label = $BackupLabel
            Notes = $BackupDescription
        }

        if (-not $PSCmdlet.ShouldProcess($instance.Id, "Back up environment")) { return; }
        $response = Backup-PowerAppEnvironment -EnvironmentName $instance.Id -BackupRequestDefinition $backupRequest;
        # The response was returned unchecked: a refused backup raised nothing (M43)
        Assert-XrmAdminResponseInternal -Response $response -Operation "Backup '$BackupLabel' of environment '$InstanceDomainName'" | Out-Null;
        $response;
    }
    end {
        $StopWatch.Stop();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }    
}

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