• Skip to primary navigation
  • Skip to main content
  • Skip to footer

Stephanos Constantinou Blog

PowerShell Scripting

  • Home
  • Blogs
    • PowerShell Tutorials
    • PowerShell Scripts
    • PowerShell Modules
      • Modules Cmdlets
    • Software Reviews
  • About
  • Contact
You are here: Home / PowerShell Scripts / Enable mailbox audit logging Office 365 with PowerShell

Enable mailbox audit logging Office 365 with PowerShell

25/01/2018 by Stephanos Leave a Comment

Enable mailbox audit logging Office 365 with PowerShell

Scenario:

Enable mailbox audit logging Office 365 with PowerShell.

Mailbox audit logging helps administrator to keep track of changes that are made on mailboxes but not only limited to that. Audit logging of mailboxes helps troubleshooting of emails. The reason that I wrote the below script, was to enable mailbox audit logging automatically on new mailboxes in the system. All mailboxes have enabled the audit logging and with this script that is running everyday, audit logging is enabled for all new mailboxes that will be created.

Audit logging can be enabled on different levels. In the script, full mailbox audit logging has been enabled. Changes made by Owner, Delegate person and Admin will be logged. Owner is the actual owner of the mailbox. Delegate is the any other user that permissions have provided to him / her on the specific mailbox. Admin is any administrator on exchange that has access to perform changes on the mailbox if there is a delegation.

Script runs on Azure Automation

The below script has been set up to run directly on Microsoft Azure. Microsoft Azure provides you with the ability to have scripts run directly on it. Under Azure automation you can have your runbooks. Runbooks can be a plain PowerShell script but also it allows you to create a runbook visually. In Azure automation credentials are saved in a secure way and can be retrieved from any runbook / script that you have configured. You can have multiple credentials saved and you are able to use any credentials that you may need in a script. When you run a script on Azure automation, a virtual environment is launched at the back-end there is no need to have a VM set up to run the scripts on it.

This next part is provided by Microsoft:

Azure Automation delivers a cloud-based automation and configuration service that provides consistent management across your Azure and non-Azure environments. It consists of process automation, update management, and configuration features. Azure Automation provides complete control during deployment, operations, and decommissioning of workloads and resources.

In general the script will gather everyday all mailboxes with audit logging disabled and will enable it. 

Let’s see in more detail what the script does

Firstly, the script will save two credentials in two different variables. The first one are the credentials that are saved in Azure automation for the admin user that will be used to connect and perform the changes. The second one are the credentials that are saved in Azure Automation for the user that will be used to send emails reports.

The next part, I found that is an important part for me not to have any issues with the Azure Automation and run of the scripts. Sometimes the script session hangs and stays active and this might create issues on the next run of the script. So the script checks if there is any active session and closes the session. Then the script will connect and import the session for Exchange Online using the admin credentials saved before.

After the connection to Exchange Online, the script will save all mailboxes in a variable. This variable ($Mailboxes) is used then to keep the UniversalPrincipalNames (UPN) of the mailboxes. I am using the UPN as this attributes is unique and will not create any conflicts during the run. When the list of UPNs is ready, a foreach loop is used to enable mailbox audit logging Office 365. Please note that all options are used in audit logging to keep full audit logs on all levels.

If there will be any errors during the run of the script, an email report will be sent including all the errors or exceptions that may appear.

You can download the script here or copy it from below.

Let me know if there are any questions or comments below.

Related Links:

  • Email error variable in PowerShell
  • Azure Automation Overview | Microsoft Docs
  • Credential assets in Azure Automation | Microsoft Docs
  • Get-PSSession – Microsoft Docs
  • Remove-PSSession – Microsoft Docs
  • New-PSSession – Microsoft Docs
  • Import-PSSession – Microsoft Docs
  • Out-Null – Microsoft Docs
  • Get-Mailbox – TechNet – Microsoft
  • Set-Mailbox – TechNet – Microsoft
  • Send-MailMessage – Microsoft Docs
  • Get-Date – Microsoft Docs

Solution / Script:

$Credentials = Get-AutomationPSCredential -Name 'Admin-User'
$EmailCredentials = Get-AutomationPSCredential -Name 'Email-User'
$To = '[email protected]','[email protected]'
$From = '[email protected]' Get-PSSession | Remove-PSSession
$Session = New-PSSession –ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $Credentials -Authentication Basic -AllowRedirection

Import-PSSession -Session $Session -DisableNameChecking:$true -AllowClobber:$true | Out-Null

$Mailboxes = Get-Mailbox -ResultSize Unlimited
$Mailboxes_UPN = $Mailboxes.UserPrincipalName

foreach ($Mailbox in $Mailboxes_UPN) {

    Set-Mailbox -Identity "$Mailbox" -AuditEnabled $true -AuditOwner Create,HardDelete,MailboxLogin,Move,MoveToDeletedItems,SoftDelete,Update `
                                    -AuditDelegate Create,FolderBind,HardDelete,Move,MoveToDeletedItems,SendAs,SendOnBehalf,SoftDelete,Update `
                                    -AuditAdmin Copy,Create,FolderBind,HardDelete,MessageBind,Move,MoveToDeletedItems,SendAs,SendOnBehalf,SoftDelete,Update
}

if ($error -ne $null) {

    foreach ($value in $error) {
    
        $ErrorEmailTemp = @"
        <tr>
            <td class="colorm">$value</td> </tr>
"@

        $ErrorEmailResult = $ErrorEmailResult + "`r`n" + $ErrorEmailTemp
    }

    $ErrorEmailUp = @"
    <style>
        body { font-family:Segoe, "Segoe UI", "DejaVu Sans", "Trebuchet MS", Verdana, sans-serif !important; color:#434242;}
        TABLE { font-family:Segoe, "Segoe UI", "DejaVu Sans", "Trebuchet MS", Verdana, sans-serif !important; border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}
        TR {border-width: 1px;padding: 10px;border-style: solid;border-color: white; }
        TD {font-family:Segoe, "Segoe UI", "DejaVu Sans", "Trebuchet MS", Verdana, sans-serif !important; border-width: 1px;padding: 10px;border-style: solid;border-color: white; background-color:#C3DDDB;}
        .colorm {background-color:#58A09E; color:white;}
        .colort{background-color:#58A09E; padding:20px; color:white; font-weight:bold;}
        .colorn{background-color:transparent;}
    </style>
    <body>
    
    <h3 style="color:#BD3337 !important;"> WARNING!!!</h3>
    
    <p>There were errors during users attributes changes check</p>
    
    <p>Please check the errors and act accordingly</p>
    <table>
"@

    $ErrorEmailDown = @"
    </table>
    </body>
"@

    $ErrorEmail = $ErrorEmailUp + $ErrorEmailResult + $ErrorEmailDown
    
    send-mailmessage `
        -To $To `
        -Subject "Enable Mailbox Audit Logs Report $(Get-Date -format dd/MM/yyyy) - WARNING" `
        -Body $ErrorEmail `
        -BodyAsHtml `
        -Priority high `
        -UseSsl `
        -Port 587 `
        -SmtpServer 'smtp.office365.com' `
        -From $From `
        -Credential $EmailCredentials
}

Filed Under: PowerShell Scripts Tagged With: Azure Automation, Get-AutomationPSCredential, Get-Date, Get-Mailbox, Get-PSSession, Import-PSSession, Microsoft Azure, Microsoft Office 365, New-PSSession, Out-Null, Remove-PSSession, Send-MailMessage, Set-Mailbox

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published.

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

Footer

Recent Posts

  • ICS Cube Product Review 26/04/2019
  • PowerShell Module SysInfo v1.2.0 15/03/2019
  • PowerShell Module SysInfo v1.1.2 13/11/2018
  • PowerShell Module SysInfo 24/10/2018
  • Get-VoltageProbe 24/10/2018
  • Get-VideoController 24/10/2018
  • Get-USBController 24/10/2018
  • Get-TrackPoint 24/10/2018
  • Get-TrackBall 24/10/2018
  • Get-TouchScreen 24/10/2018
Planet PowerShell

Categories

  • Modules Cmdlets (57)
  • PowerShell Modules (5)
  • PowerShell Scripts (38)
  • PowerShell Tutorials (35)
  • Software Reviews (2)

Archives

  • April 2019 (1)
  • March 2019 (1)
  • November 2018 (1)
  • October 2018 (56)
  • September 2018 (13)
  • August 2018 (9)
  • July 2018 (6)
  • June 2018 (8)
  • May 2018 (7)
  • April 2018 (9)
  • March 2018 (4)
  • February 2018 (6)
  • January 2018 (12)
  • December 2017 (4)
Top 10 PowerShell 2018

Blogroll

  • Planet PowerShell
  • Reddit – PowerShell
  • PowerShell Magazine
  • PowerShell.org
  • PowerShell Team Blog
  • Hey, Scripting Guy! Blog
  • Mike F Robbins
  • PowerShell Explained with Kevin Marquette
  • Mike Kanakos – Network Admin
  • The Lonely Administrator
  • AskME4Tech
PowerShell Blogs Sysadmin Blogs Banners for Top 20 Programming Blogs

© 2021 · Stephanos Constantinou Blog

  • Home
  • Blogs
  • About
  • Contact
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Ok