src/Administration/Assert-XrmAdminConnected.ps1

<#
    .SYNOPSIS
    Check that the session is connected with Connect-XrmAdmin.

    .DESCRIPTION
    This command is done each time we need to run admin operation.
    This mean that we need to proceed to Connect-XrmAdmin before.
    It loads the module Microsoft.PowerApps.Administration.PowerShell, then raises an error when Connect-XrmAdmin was not run. The admin roles of the account are not checked.

    .OUTPUTS
    System.Void. An error is raised when the session is not connected with Connect-XrmAdmin.

    .EXAMPLE
    Assert-XrmAdminConnected;
    $environments = Get-AdminPowerAppEnvironment;

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

function Assert-XrmAdminConnected {
    [CmdletBinding()]
    [OutputType([System.Void])]
    param
    (
    )
    begin {   
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew(); 
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters); 
    }    
    process {

        Import-XrmPowerAppsAdminModuleInternal;
        if (-not $Global:XrmContext.IsAdminConnected) {
            throw "You are not connected as Admin! Please use Connect-XrmAdmin command before";           
        }
    }
    end {
        $StopWatch.Stop();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }    
}

Export-ModuleMember -Function Assert-XrmAdminConnected -Alias *;