Reporting Last Login Time to Office 365

Imagine this scenario for a second: you are an admin responsible for keeping your Active Directory environment clean, including regular maintenance on user accounts – part of which requires you to disable accounts that have not logged in for a certain time period.

You have a report that tells you when your users have last logged in, and you begin to disable those AD accounts that have not logged in for that time period.

Users begin to call you and complain that they can no longer access their Office 365 services and you soon find out that you have disabled many accounts you should not have. This is likely because the user may not log into the on-premises Active Directory account any more – since your services are in the cloud.

There is one problem though: Last Logon information is missing from user objects in Azure Active Directory – the user account service Office 365 uses to authenticate to most services. Microsoft has yet to provide an out of the box, automated way to gather this information with a simple script.

You can pull information from the Office 365 or Azure Reporting pages in the Admin Centers, but that effort is manual and requires multiple steps. You don’t want to have to manually log in and export data, and then send to the proper admins for review.

To make matters more complicated, any attempt to automate this requires the login to Exchange Online PowerShell, which requires O365 Administrator Username and Password in plain text. Locally accessible – and a complete security risk.

To address this, we have created a script that does the following:

  • Prompts for Exchange Online Admin credentials, encrypts them, and stores the encrypted file with the script
  • Logs into Exchange Online PowerShell with your Exchange Online administrator service account encrypted credentials
  • Grabs a list of last logon times for users with the UPN and LastLogonDate by which you can format as a table and filter by LastLogonDate
  • Outputs Data to CSV file
  • Attached CSV file to SMTP relay procedure and sends email to recipients
  • This script is run with no command switches and in a single script, making it a great candidate for a quick scheduled task

Simply enter in the variables, run the script one time first to verify it works correctly in your environment, and then create a scheduled task out of it!

Note: You must run this script on the host you wish to schedule to, as the credentials are encrypted for the machine only.

 

Running the script the first time:

 

Viewing the stored credentials:

 

Script files (CSV, Credentials):

 

Email Message:

 

Attachment Contents:

 

 

Script:

Please, tell us what you think in the comments below!

Leave A Reply

Your email address will not be published. Required fields are marked *