Monitoring failed user logins is essential for identifying unauthorized access attempts and ensuring the security of your Microsoft 365 environment. This article introduces a simple Graph PowerShell script that retrieves failed sign-in attempts using the Microsoft Graph SDK v1.0 and displays relevant login details such as time, user, error code, IP address, and the application used.
# Connect to Microsoft Graph with necessary permissions
Connect-MgGraph -Scopes "AuditLog.Read.All"
# Retrieve all failed sign-in attempts (errorCode not equal to 0)
$FailedLogins = Get-MgAuditLogSignIn -Filter "status/errorCode ne 0" -All
# Display the required headers in the console
$FailedLogins | Select-Object `
@{Name = "Login Time"; Expression = { $_.CreatedDateTime }},
@{Name = "Logged In User (UPN)"; Expression = { $_.UserPrincipalName }},
@{Name = "Logon Error"; Expression = { $_.Status.ErrorCode }},
@{Name = "Logged In IP Address"; Expression = { $_.IpAddress }},
@{Name = "Login Application"; Expression = { $_.AppDisplayName }} |
Format-Table -AutoSize
Here are a few ways to enhance this basic script:
Filter logins from the last 7 days:
$Since = (Get-Date).AddDays(-7)
$FailedLogins | Where-Object { $_.CreatedDateTime -ge $Since }
Save the output to a file for offline analysis or incident reports:
... | Export-Csv -Path ".\FailedSignIns.csv" -NoTypeInformation
Retrieve failed logins for a single user:
$FailedLogins | Where-Object { $_.UserPrincipalName -eq "user@domain.com" }
| Error | Cause | Solution |
| Connect-MgGraph is not recognized | Graph module not installed | Run Install-Module Microsoft.Graph -Scope CurrentUser |
| Insufficient privileges to call this API | Missing delegated/admin permissions | Ensure you're using an account with AuditLog.Read.All permission and grant admin consent |
| status/errorCode is not valid in filter | Typo or using unsupported property in filter | Double-check spelling and property names; use status/errorCode exactly as shown |
This simple yet powerful script gives Microsoft 365 administrators direct visibility into failed login activity using Graph PowerShell. By customizing the output, applying filters, and exporting results, you can turn this into a proactive monitoring solution for your organization. Best of all, it's lightweight and easy to integrate into your security and compliance toolkit.
© m365corner.com. All Rights Reserved. Design by HTML Codex