BitTitan.Runbooks.AzureAD.Beta.psm1

<#
.SYNOPSIS
    PowerShell module for common Azure Active Directory (AzureAD) functions and resources used in BitTitan Runbooks.
.NOTES
    Version: 0.2
    Last updated: 14 October 2018
 
    Copyright (c) BitTitan, Inc. All rights reserved.
    Licensed under the MIT License.
#>


# Install/import BitTitan.Runbooks.Modules to bootstrap the install/import of the other modules
Install-Module BitTitan.Runbooks.Modules -Scope CurrentUser -AllowClobber
Import-Module BitTitan.Runbooks.Modules -Force

# Install/import the other BitTitan.Runbooks modules
Import-BT_Module BitTitan.Runbooks.MSPComplete 1>$null

<#
.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.
.PARAMETER username
    The username of the Azure AD admin account.
.PARAMETER password
    The password of the Azure AD admin account.
.PARAMETER endpoint
    The MSPComplete Endpoint for the Azure AD admin credentials.
    This endpoint can be masked or unmasked.
.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 | Get-CredentialFromMSPCompleteEndpoint
        $username = $azureADCredential.Username
    }
    # Create the AzureAD credential from the given username and password
    else {
        $azureADCredential = New-Object System.Management.Automation.PSCredential($username, $password)
    }

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

        # Logon was successful
        Write-Information "Connection and logon to AzureAD successful with username '$($username)' using the '$($(Get-AzureRmContext).Subscription.Name)' Subscription."
        return $true
    }
    catch {
        # Logon was unsuccessful
        Write-Error "Failed AzureAD account login with username '$($username)'. $($_.Exception.Message)"
        return $false
    }
}