Hey everyone! I've got a project where I need to find out when users last logged in and automatically disable accounts that haven't logged in for a while. Doing this for on-premises Active Directory is pretty straightforward, but I'm a bit lost on how to tackle it for Office 365. I have a method in mind, but I haven't set up a service account or application that has the required permissions before, so I'm a bit nervous about that. If anyone has experience bridging both platforms, I'd love to see any scripts you might be willing to share (anonymized, of course)! Any advice or guidance would be greatly appreciated. I've done some research but found a lot of conflicting opinions on how to reliably get the 'last logon' info for both environments.
4 Answers
So, I haven’t dealt with this in a while, but accounts used to be synced between on-prem and the cloud, meaning if Bob hadn't logged in locally for three months, the cloud would reflect that too. Just keep that in mind while checking last login dates!
What if a user logs in but doesn’t actually access any Office 365 resources? That’s where things get tricky. Check the last login values from AD and the login events from AAD/365 and compare them. Using PowerShell's Graph cmdlets alongside AD cmdlets will give you the detailed info you need. There are also older posts here covering last login times which could be helpful!
You'll want to use the Microsoft Graph API for this. It's the most reliable way to interact with Office 365 and check user logins.
Your setup plays a big role here. If you're synchronizing accounts to Azure and using password sync, the process differs. You might be using ADFS to log into Office, in which case you can just check the local last sign-in date. For Azure checks, use the MGGraph module along with the AD module to pull last login dates for both environments. Don’t forget to set up an Application Registration in Azure to get the necessary permissions and authentication setup for automation!

Good point! I hadn't thought about that. I’ll definitely make sure to check both AD and Entra ID logins to ensure I don’t miss anyone who might be using their PC without accessing M365 services.