src/Administration/Set-XrmInstanceMode.ps1

<#
    .SYNOPSIS
    Enable or disable admin mode on given instance

    .DESCRIPTION
    Administration mode will prevent users to access to instance.
    Wait for the change to end. A refused request, a failed change, or a change not ended after TimeoutInMinutes raises an error (before 2.0.0.81 the response was not checked).

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

    .PARAMETER Mode
    Admin mode (Normal : users can access / AdminOnly : Only admins can access)

    .PARAMETER TimeoutInMinutes
    Maximum time to wait for the change to end. (Default: 60)

    .OUTPUTS
    System.Void.

    .EXAMPLE
    $xrmClient = New-XrmClient -ConnectionString $connectionString;
    Connect-XrmAdmin;
    Set-XrmInstanceMode -InstanceDomainName "contoso-uat" -Mode AdminOnly;
    $xrmClient | Import-XrmSolution -SolutionUniqueName "contoso_core" -SolutionFilePath "C:\drop\contoso_core_managed.zip";
    Set-XrmInstanceMode -InstanceDomainName "contoso-uat" -Mode Normal;

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

function Set-XrmInstanceMode {
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    [OutputType([System.Void])]
    param
    (
        [Parameter(Mandatory, ValueFromPipeline)]
        [String]
        $InstanceDomainName,

        [Parameter(Mandatory = $true)]
        [ValidateSet("Normal", "AdminOnly")]
        [string]
        $Mode,

        [Parameter(Mandatory = $false)]
        [ValidateRange(1, 10080)]
        [int]
        $TimeoutInMinutes = 60
    )
    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;
        
        $runtimeState = "Enabled";
        switch ($Mode) {
            "Normal" { $runtimeState = "Enabled" }
            "AdminOnly" { $runtimeState = "AdminMode" }
        }

        if (-not $PSCmdlet.ShouldProcess($instance.Id, "Set environment mode")) { return; }
        # The change is watched here: WaitUntilFinished of the admin module fails in PowerShell 7, where the Location header is a string array
        # ("Cannot process argument transformation on parameter 'Route'"). The response was not checked: a refused or failed change raised nothing (M43)
        $response = Set-AdminPowerAppEnvironmentRuntimeState -EnvironmentName $instance.Id -RuntimeState $runtimeState -WaitUntilFinished $false;
        $operation = "Mode $Mode on environment '$InstanceDomainName'";
        $operationStatusUrl = Assert-XrmAdminResponseInternal -Response $response -Operation $operation;
        if ($operationStatusUrl) {
            try {
                Watch-XrmOperation -OperationUrl $operationStatusUrl -TimeoutInMinutes $TimeoutInMinutes -ThrowOnFailure | Out-Null;
            }
            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 Set-XrmInstanceMode -Alias *;