helpers/Connect-O365AzureAD.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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($_)
    }
}