Using Graph PowerShell to Get Microsoft 365 User Last Logon Time

Here’s a Graph PowerShell script using which Microsoft 365 administrators can fetch the last logon time of M365 users and take various security related actions like detecting suspicious accounts, deleting inactive accounts etc.,


Preqrequisites


  • Install Microsoft Graph PowerShell SDK: The Microsoft Graph PowerShell module must be installed. The command is Install-Module -Name Microsoft.Graph -Force -AllowClobber.
  • Required Graph API Permissions: Required permissions are "User.Read.All", "Reports.Read.All"

Script for your Reference

# Connect to Microsoft GraphConnect-MgGraph -Scopes "User.Read.All","Reports.Read.All"
                                
# Get all users
$users = Get-MgUser -All
                                
# Create an array to hold user logon info
$userLogons = @()
                                
foreach ($user in $users) {
        # Get sign-in activity for the user
        $signInActivity = Get-MgUser -UserId $user.Id -Property signInActivity | Select-Object -ExpandProperty signInActivity
                                    
        # If there is sign-in activity, add it to the array
        if ($signInActivity) {
                $userLogons += [PSCustomObject]@{
                            UserPrincipalName = $user.UserPrincipalName
                            DisplayName = $user.DisplayName
                            LastSignInDateTime = $signInActivity.LastSignInDateTime
        }
        } else {
                # If no sign-in activity, add user with empty sign-in fields
                $userLogons += [PSCustomObject]@{
                            UserPrincipalName = $user.UserPrincipalName
                            DisplayName = $user.DisplayName
                            LastSignInDateTime = "N/A"
        }
        }
 }
                                
# Export the results to a CSV file
$userLogons | Export-Csv -Path "C:\M365UserLastLogon.csv" -NoTypeInformation
                                
# Disconnect from Microsoft Graph
Disconnect-MgGraph
                                
Write-Output "User last logon information has been exported to C:\M365UserLastLogon.csv"

How the Script Works?

Heres how the script works:

  1. Connect-MgGraph: Connects to Microsoft Graph with the required scopes User.Read.All and Reports.Read.All
  2. Get-MgUser -All: Retrieves all users and stores them in the $userLogons array.
  3. ForEach Loop: Iterates through each user to fetch their sign-in activity.
  4. $signInActivity = Get-MgUser -UserId $user.Id -Property signInActivity | Select-Object -ExpandProperty signInActivity: Retrieves the sign-in activity for each user and expands on the signInActivity property.
  5. Conditional Check: If there is sign-in activity present, the same gets added agains the user. If there is no sign-in activity, then the column is marked off as N/A for the user.
  6. Export-Csv: The user list along with the sign-in activity info is exported to a CSV file using the Export-CSV cmdlet.
  7. Disconnect-MgGraph: Finally the session with Graph PowerShell is disconnected.


Further Enhancing the Script

Here are some suggestions to enhance the script:

  • Error Handling: Add error handling to ensure the script gracefully handles any issues, such as connection problems or missing permissions.
  • Logging:: Implement logging to record the script's actions, which can help in troubleshooting and keeping a record of script runs.
  • Filtering Users:: Allow filtering by specific user attributes (e.g., department, location) to limit the scope of the report.
  • Progress Indicator:: Add a progress indicator to provide feedback on the script's progress, especially useful when dealing with many users.
  • Parameterization:: Allow passing parameters to the script, such as the output file path, specific user properties to include, or filtering criteria.
  • Email Notification:: Send an email notification with the CSV file attached once the script completes.
  • User-Friendly Output:: Enhance the CSV output with additional user properties and more readable date formats.

Related Articles:

Connect to Microsoft 365 Using PowerShell
How to Create Bulk Users in Office 365 Using Graph PowerShell?
Create Microsoft 365 Group Using Microsoft Graph PowerShell
Block Microsoft 365 User Using Microsoft Graph PowerShell
Assign Microsoft 365 License Using Graph PowerShell
Microsoft 365 User Management Using Graph PowerShell
Checking Group Membership in Microsoft 365
Bulk Assign Microsoft 365 License
Find Inactive Users in Microsoft 365
Using Powershell Graph Search Query
Using Powershell Graph Filter Query
Using Where-Object In Graph PowerShell
Using Expand Property In Graph PowerShell
Using Select Object In Graph PowerShell
Using -Contains Operator In Graph PowerShell
Add User to Multiple Microsoft 365 Groups Using Graph PowerShell
Get Microsoft 365 User Location Using Graph PowerShell
Import Microsoft 365 Groups from CSV File Using Graph PowerShell
Microsoft 365 Group User Import Using Graph PowerShell

© m365corner.com. All Rights Reserved. Design by HTML Codex