Microsoft Graph is a powerful tool that allows administrators to manage their Azure AD tenant and automate tasks. One common task is to retrieve the last sign-in date time for all users in Azure AD. This information can be used to track user activity and identify any inactive accounts that may need to be disabled or deleted. In this article, we will explain how to use Microsoft Graph to retrieve the last sign-in date time for all users in Azure AD.
Prerequisites:
To follow along with this tutorial, you will need the following:
- An Azure AD tenant
- Global administrator privileges
- PowerShell with the Microsoft Graph PowerShell module installed.
Steps to Retrieve the Last Sign-In Date Time for All Users in Azure AD Using Microsoft Graph:
Step 1: Connect to Microsoft Graph
First, open PowerShell and connect to Microsoft Graph using the following command:
Connect-MgGraph -Scopes Directory.Read.All,AuditLog.Read.All
Step 2: Export User Data with lastSignInDateTime to CSV
Export the user data based on your requirement either for all users/member users/guest users, including the UserPrincipalName and Id, to a CSV file using the following command:
For all users-
Get-MgUser -All -Property 'UserPrincipalName','SignInActivity','Mail','DisplayName' | Select-Object @{N='UserPrincipalName';E={$_.UserPrincipalName}}, @{N='DisplayName';E={$_.DisplayName }}, @{N='LastSignInDate';E={$_.SignInActivity.LastSignInDateTime}} | Export-Csv -Path C:\usernew1.csv -NoTypeInformation -NoClobber
For all member users use-
Get-MgUser -All -Filter "UserType eq 'Member'" -Property 'UserPrincipalName','SignInActivity','Mail','DisplayName' | Select-Object @{N='UserPrincipalName';E={$_.UserPrincipalName}}, @{N='DisplayName';E={$_.DisplayName }}, @{N='LastSignInDate';E={$_.SignInActivity.LastSignInDateTime}} | Export-Csv -Path C:\usernew1.csv -NoTypeInformation -NoClobber
For all guest users use-
Get-MgUser -All -Filter "UserType eq 'Guest'" -Property 'UserPrincipalName','SignInActivity','Mail','DisplayName' | Select-Object @{N='UserPrincipalName';E={$_.UserPrincipalName}}, @{N='DisplayName';E={$_.DisplayName }}, @{N='LastSignInDate';E={$_.SignInActivity.LastSignInDateTime}} | Export-Csv -Path C:\usernew1.csv -NoTypeInformation -NoClobber
Sample Output:
![enter image description here](https://i.stack.imgur.com/MVQu7.png)
Conclusion:
In this article, we have explained how to use Microsoft Graph to retrieve the last sign-in date time for all users in Azure AD. By exporting the user data to a CSV file and looping through it to retrieve the last sign-in date time, administrators can easily track user activity and identify any inactive accounts that may need to be disabled or deleted.