Monitor Azure AD LastDirSyncTime Using PowerShell

Office365Logo_256x254pxKnowing if your Directory Sync is up to date (or not) is crucial. Yes, you can glue your eyes to the Office 365 Portal or use commercial 3rd party monitoring tools to be alerted when your Directory Sync hasn’t updated for a certain period, or you can achieve the same goal using PowerShell. Microsoft was kind enough to include a LastDirSyncTime value when you run the Get-MsolCompanyInformation cmdlet. This way it can be programmatically checked and monitored by scheduling a script to run via task at an interval.

This script queries the LastDirSyncTime value, gets the current time, calculates the elapsed time, compares the difference against a set threshold and send an email alert if the threshold is breached.

Download Link

https://github.com/junecastillote/Get-O365DirSyncElapsed

  • 1.0 - April 19, 2018
    • Initial Release
  • 1.1 – August 20, 2018
    • Changed Time Stamp from UTC to Local Time, including the Time Zone ID
    • Required PowerShell v5.1


Requirements

  • PowerShell v5.1 (as of script v1.1)
  • MSOnline Module

Having the MSOnline Module installed is required for this to work. If you have PowerShell 5, it is easy to install. Just run Install-Package MSOnline and it should get you started. However for lower PS versions it may take a bit more to get MSOnline Module installed.

You can read up on MSOnline in detail from by following this link: Azure ActiveDirectory (MSOnline)

How To Use

Export Login Credentials to XML

The Username and Password are not saved inside the script, but rather it will import the login information from an encrypted XML file that you need to create beforehand.

Run this line in PowerShell, and it should save the credentials in an XML file.

Get-Credential | Export-CliXml ExOnlineStoredCredential.xml

Below is the sample content of the exported credentials.

Variables

Some variables that need to be modified depending on your requirement. The below example assumes that you are also using Exchange Online as relay. If you prefer to use a different SMTP relay, you will need to manually modify the script to conform with that.

In this example, only the following variables need to be modified.

$dirSyncElapsedTimeThreshold: The threshold in hours. If this is breached, the email alert will be sent.

$toAddress : The email addresses (separate with comma if more than one) of the intended recipients of the email alert.

$mailSubject: Your choice of message subject when the alert is sent.


Output

Once it’s all set up, just run the script from PowerShell. In the example below I set the threshold to ZERO (0) hours to trigger the alert. You should set a more realistic threshold in your production, obviously.

Then the email alert similar to this should be received.

Share:

1 comment:

Popular Posts

Powered by Blogger.