Automating Exchange PowerShell scripts got a bit more complicated with the introduction of OAuth2 authentication and MFA (Multi-Factor Authentication).
If you require all users to authenticate using MFA (and you should) – how can you create unattended scripts?
Fortunately, starting from version 2.0.3, the Exchange Online Management module (ExoV2) includes a neat solution for this:
Azure Apps and Certificate-Based Authentication
ExoV2 (v2.0.3 and later) has new parameters to provide an AppId and a certificate Thumbprint.
These parameters allow your script to
- Execute Exchange Online PowerShell commands in the context of an Azure Application (AppId).
- Authenticate to the App using a certificate (Thumbprint).
Assuming that you have assigned the proper permissions to the Azure App, this is all we need.
Step-by-Step Guide on the Configuration of Exchange PowerShell Automation
You need to perform the following steps to set up your Exchange PowerShell automation:
- Generate a certificate to use for authentication.
- Set up an Application Registration.
- Assign API permissions to the Application (and grant admin consent).
- Assign certificate-based credentials to the Application Registration.
- Assign Exchange permissions to the Application.
These five steps are covered in detail below:
The Office 365 Management Tool for Active Directory
Perform All Daily Office 365 Management Directly From AD
Remove Your On-Premises Exchange Server
1. Generate a Certificate for Authentication
If you have a CA (Certificate Authority) infrastructure, you can use that to generate your certificate.
If not, you can generate a self-signed certificate which works just as fine: There is no need for the Azure App to trust the issuer.
You need two files from the certificate:
- A .pfx file – includes the private key and is stored securely in the personal certificate store of your scheduling account on the scheduling server.
- A .cer file – includes only the public key and is uploaded to the Azure App to allow you to authenticate using the corresponding (secret) private key.
Generate a new certificate and export the .pfx and .cer files using the following code:
# Create certificate with expiry of 5 years
$mycert = New-SelfSignedCertificate -DnsName "easy365manager.com" -CertStoreLocation "cert:\CurrentUser\My" -NotAfter (Get-Date).AddYears(5) -KeySpec KeyExchange
# Export certificate to .pfx file
$mycert | Export-PfxCertificate -FilePath C:\tmp\ExoAutomateCert.pfx -Password $(ConvertTo-SecureString -String "$omeP@ssw0rd" -AsPlainText -Force)
# Export certificate to .cer file
$mycert | Export-Certificate -FilePath C:\tmp\ExoAutomateCert.cer
The certificate is created in the personal certificate store of the user running the code.
This means that if you plan to automate scripts using the logged-in account on the logged-in system, you won’t need the .pfx file (except for backup).
To use the certificate on another system/user account, you must log in interactively and import the certificate from the .pfx file.
The .cer file will be used to set up authentication on the Azure App in a later step.
2. Set Up an Azure Application
To set up a new Azure Application, you must log in to the Azure Portal. Select Azure Active Directory and click on App registrations or follow the direct link.
From there, you can create a new App registration by clicking on New registration:
Provide a meaningful name, select Accounts in this organizational directory only, and set up a web redirect URI to be used as a response to authentication requests (not so relevant for our use).


You should now be able to verify the Azure App has been created:

Notice the Application (client) ID. This is what we will use as the -AppId parameter when connecting to Exchange Online with PowerShell.
3. Set Up API Permissions
So far, our Azure App has no permissions.
As we’ll be using it for automated Exchange Online management, we need to assign
Select API permissions, click on Add a permission, select APIs my organization uses, narrow down the results by typing Office 365, and select Office 365 Exchange Online:

From the next menu, select Application permissions, expand Exchange, select Exchange.ManageAsApp, and click Add permission:

Finally, you need to grant consent to the App.
Click on Grant admin consent and click Yes to accept:

You’ll now see a green check mark next to the API permission.
4. Assign Certificate-Based Credentials to the App Registration
The next step needed is to set up the certificate generated in step 1 as a valid credential in the Azure Application.
Click on Certificates & secrets, click on Certificates, click on Upload certificate, browse to the .cer file from step 1, add a description and click on Add:

You’ll now see the certificate in the list, including the thumbprint that we’ll be using as a parameter in our script:

5. Assign Exchange permissions to the Application
Finally, we just need to assign the proper Azure role to our Application.
If our scripts will only manage recipients (mailboxes and other recipient objects) then we’ll need to assign the Exchange Recipient Administrator role.
From the Azure Portal open up Azure Active Directory and click on Roles and administrators. Or follow this direct link.
Enter ‘exchange’ in the filter and click on Exchange recipient administrator:

Assign the Exchange recipient administrator role to our new Application by clicking Add assignments and clicking on the Application identity created in step 2:

Running Automated Scripts With Certificate-Based Authentication
You can now start setting up your automated scripts.
It’s always a good idea to check that your account holds the proper certificate. You can check your certificate store and see the thumbprint using the following code:
PS C:\> Get-ChildItem Cert:\CurrentUser\My | ft PSParentPath: Microsoft.PowerShell.Security\Certificate::CurrentUser\My Thumbprint Subject ---------- ------- D05DEA539D7D560F342E3CBED9163EB79334F9EC CN=easy365manager.com
If everything looks good, you can now connect to Exchange Online with PowerShell using your certificate with no user intervention needed:
PS C:\> Connect-ExchangeOnline -AppId "81d79cde-c79e-4608-ba15-8d1e66eab6bc" -CertificateThumbprint "d05dea539d7d560f342e3cbed9163eb79334f9ec" -Organization "skrubbeltrang.onmicrosoft.com"
----------------------------------------------------------------------------------------
This version of EXO PowerShell V2 module contains new REST API backed cmdlets which doesn't require WinRM
for Client-Server communication and therefore you can now run these cmdlets after turning off WinRM Basic
Auth in your client machine thus making it more secure.
The cmdlets in the downloaded module are resilient to transient failures, handling retries and throttling errors inherently.
The service side execution of these cmdlets have been optimized to perform better than the RPS (V1) cmdlets.
Unlike the EXO* prefixed cmdlets, the cmdlets in this module supports full functional parity with the RPS (v1) cmdlets.
For more information check https://aka.ms/exov2-module
Send your issues, product improvement suggestions and feedback to exocmdletpreview@service.microsoft.com
----------------------------------------------------------------------------------------
PS C:\> get-mailbox lene.hau
Name Alias Database ProhibitSendQuota ExternalDirectoryObjectId
---- ----- -------- ----------------- -------------------------
Lene Hau lene.hau EURP189DG065-db131 49.5 GB (53,150,2... 2df91b7a-78a7-47cf-b58c-e294f302fd71
Summary
Setting up the prerequisites to run automated PowerShell scripts is a bit tedious, as seen in this overview.
However, once you have all the bits and pieces lined up, the execution of scripts is super easy:
Just import the private key certificate on your system and set up the parameters in your connection – you’re good to go!
If already now you’re thinking: “How do I audit what my automated script is doing?” you should read this article.
Consolidate Your AD and Office 365 Management
Hybrid Office 365 management is a real pain to many companies and organizations.
More and more are starting to consolidate AD and Office 365 management.
Most solutions introduce new web applications, are difficult to learn, and cost a fortune.
However, one solution exists that simply extends the functionality of AD Users & Computers – the admin tool loved by admins for more than two decades.
With Easy365Manager you get extra tabs on user properties that address all your needs for daily management of Office 365 and Exchange Online:


With these new tabs, anyone, including your junior IT supporters, can start setting up user calendar permissions. Something that normally requires second-level PowerShell scripting skills:
Easy365Manager is a simple .dll extension to AD Users & Computers.
It requires no infrastructure changes and can be installed in less than a minute.