Close Menu
    Facebook X (Twitter) Instagram
    Trending
    • Workplace Ninja User Group Denmark – April 2026 Meetup
    • Workplace Ninja User Group Denmark March 2026 Meetup
    • Workplace Ninja User Group Denmark February 2026 Meetup
    • Successful Adoption of a “Cloud First” Strategy
    • Speaking at Nordic Virtual Summit
    • Workplace Ninja User Group Denmark February Meetup
    • Workplace Ninja User Group Denmark Meetup – May 2022
    • Workplace Ninja User Group Denmark Meetup – April 2022
    RONNIPEDERSEN.COM
    • Home
    • Enterprise Mobility
      • Configuration Manager
      • Identity and Access
      • Information Protection
      • Intune
    • Cloud and Data Center
      • Data Center Management
      • Group Policy
      • Enterprise Security
      • Hyper-V
      • PowerShell
    • Guides
    • Webcasts
    • Links
    • About
      • Contact me
      • Disclaimer
    RONNIPEDERSEN.COM
    You are at:Home»Cloud and Data Center»Automate Mailbox Auditing in Office 365

    Automate Mailbox Auditing in Office 365

    9
    By Ronni Pedersen on July 29, 2017 Cloud and Data Center, Identity and Access, Information Protection, PowerShell

    Introduction

    For most organizations, Office 365 (mailboxes) can contain both high business impact and personally identifiable information, so it’s important that we track who logs on to the mailboxes in the organization and what actions are taken. By default, mailbox auditing in Office 365 isn’t turned on, so this guide will help you to setup and verify mailbox auditing in Office 365.

    This guide will walk you through the following steps:

    • Step 1: Connect to Exchange Online
    • Step 2: Get the current state of audit logging
    • Step 3: Enable mailbox audit logging
    • Step 4: Set the age limit for mailbox audit logging
    • Step 5: Automate the process using Azure Automation

    Connect to Exchange Online

    All Office 365 Tenant Admins should have multi-factor authentication (MFA) enabled, and if you want to connect to Exchange Online PowerShell, you need to install the Exchange Online Remote PowerShell Module, and use the Connect-EXOPSSession cmdlet to connect.

    The Exchange Online Remote PowerShell Module must be installed on your computer, and is available from the Exchange admin center (EAC).

    Here is a detailed install guide:
    https://technet.microsoft.com/en-us/library/mt775114(v=exchg.160).aspx

    Now you can launch the Exchange Online Remote PowerShell Module, and use the following command to connect to Exchange Online:

    Connect-EXOPSSession -UserPrincipalName <UPN>

    clip_image002

    Get the current state of audit logging

    Before we enable Mailbox Auditing for all our users, we might want to see the current configuration for each mailbox. This is also a good way to verify that it actually works. This can be done by running the following PowerShell command:

    Get-Mailbox -Filter {RecipientTypeDetails -eq “UserMailbox”} | Select Name,AuditEnabled

    clip_image004
    As you can see, not all of my users have mailbox audit enabled. We need to fix that!

    Enable mailbox audit logging

    Now we’ll use PowerShell to enable mailbox audit logging for all user mailboxes in the organization.
    This can be done by running the following PowerShell command:

    Get-Mailbox -Filter {RecipientTypeDetails -eq “UserMailbox”} | Set-Mailbox -AuditEnabled $True

    clip_image006
    If we then run the first PoweShell command again, we can check the status again.
    Now all user mailboxes should now have mailbox audit logging enabled.

    clip_image008

    Set the age limit for mailbox audit logging

    By default, entries in the mailbox audit log are kept for 90 days. So, when an entry is older than 90 days, it’s deleted. Many organizations would like change that to 180 or maybe even 365 days. This can be configured by using the Set-Mailbox cmdlet to change the setting so items are kept for a longer period.

    This example increases the age limit for mailbox audit log entries for all user mailboxes in the organization to 365 days.

    Get-Mailbox -Filter {RecipientTypeDetails -eq “UserMailbox”} | Set-Mailbox -AuditLogAgeLimit 365

    clip_image010

    Automate the process using Azure Automation

    Now mailbox auditing is configured like we want it for all our current users. But what about new users? The commands we used to enable and configure mailbox auditing, won’t affect all new users that we create in the future. That means that we need to remember to set this for all new users that we create.

    Or we can do it like a boss! We can automate the process, and catch all users that we “forget” to configure correctly. And the easiest (and coolest) way to do that, is by using Azure Automation.

    If this is the first time you’re using Azure Automation, you need to start by creating an Azure Automation Account. More Information: https://docs.microsoft.com/en-us/azure/automation/automation-create-standalone-account

    Next, you need to create an Credential Assets, that can execute your Runbooks. More information: https://docs.microsoft.com/en-us/azure/automation/automation-credentials

    Now you should be ready to create the Azure Automation Runbook.
    Select Runbooks and Click Add a Runbook.

    clip_image012
    Add a Name to the Runbook, and select PowerShell as the Runbook Type. Click Create.

    clip_image014

    Use the following script (don’t forget to change the “AAD Service Account” to the name of your credentials):

    # ----------------------------------------------------------------------------- 
    # Author: Ronni Pedersen, Microsoft MVP: Enterprise Mobility
    # Blog: https://www.ronnipedersen.com 
    # Twitter: @ronnipedersen 
    # Date: 29/07-2017
    # ----------------------------------------------------------------------------- 
    # Enable Mailbox Auditing for Office 365 Users
    # ----------------------------------------------------------------------------- 
    
    #Connect to Azure Automation
    $Credentials = Get-AutomationPSCredential -Name 'AAD Service Account'
    
    # Function: Connect to Exchange Online 
    function Connect-ExchangeOnline {
        param (
            $Creds
        )
            Write-Output "Connecting to Exchange Online"
            Get-PSSession | Remove-PSSession       
            $Session = New-PSSession –ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $Creds -Authentication Basic -AllowRedirection
            $Commands = @("Get-MailboxFolderPermission","Set-MailboxFolderPermission","Set-Mailbox","Get-Mailbox","Set-CalendarProcessing","Add-DistributionGroupMember")
            Import-PSSession -Session $Session -DisableNameChecking:$true -AllowClobber:$true -CommandName $Commands | Out-Null
        }
    
    # Connect to Exchange Online
    Connect-ExchangeOnline -Creds $Credentials
    
    # Enable Mailbox Audit for All Users
    Write-Output "Enable Mailbox Audit for all Users"
    Get-Mailbox -Filter {RecipientTypeDetails -eq "UserMailbox" -and AuditEnabled -eq $False} | Set-Mailbox -AuditEnabled $True
    
    # Set AuditLogAgeLimit to 1 year
    Write-Output "Set Mailbox Audit Log Age Limit for all Users"
    Get-Mailbox -Filter {RecipientTypeDetails -eq "UserMailbox"} | Set-Mailbox -AuditLogAgeLimit 365
    
    # Close Session
    Get-PSSession | Remove-PSSession
    
    Write-Output "Script Completed!"

    Important: Don’t forget to schedule the runbook to run every night.

    That’s it…

    +Ronni Pedersen

    • Tweet
    • Share 0
    • +1
    • LinkedIn 0

    Related

    Ronni Pedersen
    • Website
    • Facebook
    • X (Twitter)
    • LinkedIn

    My name is Ronni Pedersen and I'm currently working as a Cloud Architect at APENTO in Denmark. My primary focus is Enterprise Client Management solutions, based on technologies like AzureAD, Intune, EMS and System Center Configuration Manager. I'm is also a Microsoft Certified Trainer and Microsoft MVP in Enterprise Mobility.

    Related Posts

    Workplace Ninja User Group Denmark February Meetup

    CoLabora Recordings – December 2021

    CoLabora User Group Meeting – December 2021

    9 Comments

    1. Andrew Wells on July 31, 2017 13:45

      Thought I would leave a suggestion for you regarding the PowerShell command you use to get all the mailboxes. Where it says “Get-Mailbox -Filter {RecipientTypeDetails -eq “UserMailbox”} “, you may want to change it to read “Get-Mailbox -Filter {RecipientTypeDetails -eq “UserMailbox” -and AuditEnabled -eq $false}”. That would prevent a large organization from re-applying the settings when they have already been applied.

      Reply
      • Ronni Pedersen on July 31, 2017 19:07

        Great suggestion! I’ll update the post.
        Thanks!

        Reply
    2. Torben Slaikjer on August 25, 2017 13:08

      Hi Ronnie,

      What I great idea to use automation for this.
      Tried to implement the code on our Directory – there were a few thing things I had to change before I succeeded:

      a) The get-mailbox command only returns 1000 users pr. default. Use get-mailbox -resultsize unlimited ….. to be sure all users are returned.

      b) When used in a pipe, set-mailbox uses “user display name” to identify the user account. This will probably not be unique. I had several warning about non-unique accounts.
      I had to use ….|% {set-mailbox $_.UserPrincipalName …… } to identify the accounts uniquely.

      c) When setting the AuditLogAgeLimit, runtime can be greatly reduced by adding a where filter. This will avoid writing to accounts having a 365 days limit set.
      get-Mailbox -resultsize unlimited -Filter {RecipientTypeDetails -eq “UserMailbox”} |? {$_.AuditlogAgeLimit -notlike “365*” } |% {Set-Mailbox $_.UserPrincipalName -AuditLogAgeLimit 365}

      Reply
      • Ronni Pedersen on August 26, 2017 14:52

        Hi Torben,

        I’m super happy that you got inspired by this blog post. This is what the community is all about 🙂

        All you inputs are great and super valid. Thanks for sharing them with us.
        When I get time, I’ll try to update the blog post and the sample scripts, to include your findings.

        Thanks again.

        Ronni Pedersen

        Reply
    3. Daniel on February 28, 2018 20:38

      Is this part of the premium service for Azure? It says I need a subscription and that some features aren’t billable ie free with subscription. It doesn’t tell you how much it costs before taking your credit card info. This worries me.

      Reply
      • Ronni Pedersen on March 2, 2018 10:44

        This is a paid service, but you get some free. You need a subscription to use the free part anyway!

        Reply
    4. stephane munger on May 25, 2018 17:50

      Hello,

      I have a question for you ?

      With Exchange Online, if legal people (Lawyer) want to have access to the content of the message when they do surveys.

      How can they do it?
      Should I use an external utility?

      Reply
      • Ronni Pedersen on June 4, 2018 15:31

        The question is too complicated to be answered as a comment. Try to ask in one of the office 365 forums!

        Reply
    5. nicksbiz on October 6, 2019 11:42

      Thank you for the script.

      I want to get EXO mailbox statistics and export it into a CSV file and then send email with the attachment. I modified the script and it runs without any error but no result. I do not get my file exported at first place.

      Please assist.

      Regards

      Reply
    Leave A Reply Cancel Reply

    This site uses Akismet to reduce spam. Learn how your comment data is processed.

    Follow
    APENTO

    Follow APENTO here:

    Subscribe to Blog via Email

    Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    About
    My name i s Ronni Pedersen and I'm currently working as a Cloud Architect at APENTO in Denmark. My primary focus is Endpoint Management and Security, based on Microsoft technologies. I'm also a Microsoft Certified Trainer and a dual Microsoft MVP in both Security and Windows.
    Recent Posts
    • Workplace Ninja User Group Denmark – April 2026 Meetup
    • Workplace Ninja User Group Denmark March 2026 Meetup
    • Workplace Ninja User Group Denmark February 2026 Meetup
    • Successful Adoption of a “Cloud First” Strategy
    • Speaking at Nordic Virtual Summit
    Archives
    TOP POSTS
    • SCCM 2012: How does Automatic Client Upgrade work?
    • Installing SCCM 2012 SP2/R2 SP1 – Quick Start Guide
    • Microsoft Security Essentials available FREE to Small Businesses
    • Configuration Manager 2007 Service Pack 1 released
    • Microsoft Deployment Toolkit 2010 Update 1 vs. Modena
    RECENT COMMENTS
    • cOSHi on Missing “UserType” attribute in Azure AD
    • Gus on Pro Tip: Use Ctrl+Alt+D from the Azure Portal to get performance information
    • Sebi on Prepare for Co-Management: Migrate Intune Devices without user affinity
    • Vadim P on SCCM: Failed to Get Client Identity (80004005)
    • TM on Active Directory Based Activation in an multi domain environment
    DISCLAIMER
    The content on this website is presented "as-is" with no guarantees. The use of scripts from this website is at your own risk. Always test before putting something in production! Opinions expressed are my own.
    © 2026 ThemeSphere. Designed by ThemeSphere.

    Type above and press Enter to search. Press Esc to cancel.