AzureAutomationAgainstExchangeOnlineWithMFAEnabledAccount.ps1


<#PSScriptInfo
 
.VERSION 1.0.0
 
.GUID b480bfbb-5afb-4f9a-aecd-493668158ec5
 
.AUTHOR michael_mardahl
 
.COMPANYNAME
 
.COPYRIGHT
 
.TAGS exchange online runbook mfa
 
.LICENSEURI
 
.PROJECTURI
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
 
#>


#Requires -Module ExchangeOnlineShell

<#
 
.DESCRIPTION
 Connect to Exchange Online from Azure Automation using a priviledged account with MFA enforced
 
#>
 

Param()


<#
    .DESCRIPTION
        A runbook that can connect to Exchange Online without MFA prompt.
        Scenario: User is a memeber of "Exchange Administrators" Role. And MFA for all Priv. accounts is enabled.
 
    .NOTES
        AUTHOR: @michael_mardahl https://www.iphase.dk
        LASTEDIT: Oct 8, 2019
 
        REQUIRED MODULES: ExchangeOnlineShell
 
        It's very important that the user account used, has never logged on, and never shall logon!
        Create an appropriate user using this bit of PowerShell (modify with your own data) - do it using the Azure Cloud Shell:
         
        $PasswordProfile = New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile
        $PasswordProfile.Password = "Password"
        $PasswordProfile.ForceChangePasswordNextLogin = $false
        $user = New-AzureADUser `
         -DisplayName "New User" `
         -PasswordProfile $PasswordProfile `
         -UserPrincipalName "NewUser@contoso.com" `
         -AccountEnabled $true `
         -MailNickName "User alias"
 
         Afterwards you need to create a Credential for this RunBook within Azure Automation.
 
#>



# Name of the credential that you created in Azure Automation.
$CredentialName = 'EXOAutomation'

$UserCredential = Get-AutomationPSCredential -Name $CredentialName

try
{
    "Logging in to Exchange Online..."
    Connect-ExchangeOnlineShell -Credential $UserCredential
}
catch {
    if (!$UserCredential)
    {
        $ErrorMessage = "User credential $CredentialName not found."
        throw $ErrorMessage
    } else{
        Write-Error -Message $_.Exception
        throw $_.Exception
    }
}