Tracking successful user sign-ins is vital for monitoring user activity, auditing sign-in patterns, and ensuring secure access to Microsoft 365 services. This article walks you through a basic Graph PowerShell script to extract successful user login data using the Microsoft Graph PowerShell SDK (v1.0), with enhancements and troubleshooting guidance.
# Connect to Microsoft Graph with necessary permissions
Connect-MgGraph -Scopes "AuditLog.Read.All"
# Retrieve all successful sign-in attempts (status/errorCode = 0)
$SuccessfulLogins = Get-MgAuditLogSignIn -Filter "status/errorCode eq 0" -All
# Display the required headers in the PowerShell console
$SuccessfulLogins | Select-Object `
@{Name = "Login Time"; Expression = { $_.CreatedDateTime }},
@{Name = "Logged In User (UPN)"; Expression = { $_.UserPrincipalName }},
@{Name = "Logged In IP Address"; Expression = { $_.IpAddress }},
@{Name = "Login Application"; Expression = { $_.AppDisplayName }} |
Format-Table -AutoSize
Here are some enhancements you can apply to tailor the script to your needs:
To focus on recent activity, you can filter results to include only those in the last 7 days:
$Since = (Get-Date).AddDays(-7)
$RecentSuccessLogins = $SuccessfulLogins | Where-Object { $_.CreatedDateTime -ge $Since }
Exporting to a .csv file is helpful for audits and sharing reports:
$SuccessfulLogins | Select-Object ... | Export-Csv -Path ".\SuccessfulLogins.csv" -NoTypeInformation
You can further narrow results by specific user or application:
$SuccessfulLogins | Where-Object { $_.UserPrincipalName -eq "jane.doe@domain.com" }
| Error | Cause | Solution |
| Connect-MgGraph is not recognized | Microsoft Graph SDK is not installed | Run Install-Module Microsoft.Graph -Scope CurrentUser |
| Access Denied or Insufficient privileges | Missing admin consent or permission | Ensure AuditLog.Read.All is granted and consented by an admin |
| status/errorCode is not valid | Incorrect OData filter syntax | Use status/errorCode eq 0 (note case-sensitivity and exact path) |
-Top with -All for Large Log Retrievals-All with a smaller -Top (e.g. -Top 1000) helps manage pagination and API load while ensuring you fetch all records without overwhelming the session.
ipAddress to Detect Unusual Sign-In SourcesipAddress field (e.g., in your Select-Object) can help pinpoint sign-ins from unexpected locations.
Exporting this data supports security audits and can highlight potentially unauthorized or suspicious access.
With just a few lines of PowerShell, you can retrieve valuable insight into successful user sign-ins across your Microsoft 365 environment. This script is an excellent starting point for building robust sign-in activity reports that enhance your auditing, security monitoring, and compliance workflows.
© m365corner.com. All Rights Reserved. Design by HTML Codex