AzureAutomationAgainstExchangeOnlineWithMFAEnabledAccount.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94

<#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
    }
}