helpers/Connect-O365AzureAD.ps1

function Connect-O365AzureAD
{
    [CmdletBinding()]
    PARAM
    (
        [System.Management.Automation.PSCredential]
        $Credential,

        [switch]
        $UseMSOnlineModule
    )

    try
    {
        if ($PSBoundParameters.ContainsKey("UseMSOnlineModule"))
        {
            $ModuleName = "MSOnline"
            Import-Module -Name $ModuleName -DisableNameChecking -Force -ErrorAction Stop
            Connect-MsolService -Credential $Credential
        }
        else
        {
            $ModuleName = "AzureAD"
            Import-Module -Name $ModuleName -DisableNameChecking -Force -ErrorAction Stop
            $null = Connect-AzureAD -Credential $Credential
        }
    }
    catch [System.IO.FileNotFoundException]
    {
        Write-Error -Message "The module '$ModuleName' was not found. A connection to Azure Active Directory will not be established"
    }
    catch
    {
        $PSCmdlet.ThrowTerminatingError($_)
    }
}