Functions/Connect-AzureADAdminAccount.ps1

<#
.SYNOPSIS
    This function connects to Azure AD using admin account credentials or a MSPComplete Endpoint.
.DESCRIPTION
    This function connects to Azure AD using admin account credentials or a MSPComplete Endpoint.
    It returns whether the connection and logon was successful.
.EXAMPLE
    Connect-AzureADAdminAccount -Endpoint $Endpoint
.EXAMPLE
    $Endpoint | Connect-AzureADAdminAccount
.EXAMPLE
    Connect-AzureADAdminAccount -Username $username -Password $password
#>

function Connect-AzureADAdminAccount {
    param (
        # The username of the AzureAD account.
        [Parameter(Mandatory=$true, ParameterSetName="credential")]
        [String]$username,

        # The password of the AzureAD account.
        [Parameter(Mandatory=$true, ParameterSetName="credential")]
        [SecureString]$password,

        # The MSPComplete Endpoint.
        [Parameter(Mandatory=$true, ParameterSetName="endpoint", ValueFromPipeline=$true)]
        $endpoint
    )

    # If given endpoint, retrieve credential directly
    if ($PSCmdlet.ParameterSetName -eq "endpoint") {
        $azureADCredential = $endpoint.Credential
        $username = $azureADCredential.Username
    }

    # Create the AzureAD credential from the given username and password
    else {
        $azureADCredential = [PSCredential]::new($username, $password)
    }

    # Store the username used globally
    $Global:AzureADUsername = $username

    # Logon to AzureAD
    try {
        Connect-AzureAD -Credential $azureADCredential -ErrorAction Stop

        # Logon was successful
        Write-Information "Connection and logon to Azure AD successful with username '$($username)'."
        return $true
    }

    # Logon was unsuccessful
    catch {
        Write-Error "Failed Azure AD account login with username '$($username)'.`r`n$($_.Exception.Message)"
        return $false
    }
}