Simplify user tasks like bulk creation, updates, password resets, deletions, license checks & more β all from one place.
π Launch ToolkitTracking user sign-in activity is crucial for auditing, security monitoring, and compliance in Microsoft 365. Administrators can gain valuable insights by analyzing successful and failed logins across the tenant.
With Microsoft Graph PowerShell, this process becomes simple and automated. The script below fetches sign-in logs from Entra ID (Azure AD) for the past seven days, generates a report containing success and failure details, and emails it to the administrator.
$AdminUPN = "admin@yourtenant.onmicrosoft.com"
$LookbackDays = 7
Connect-MgGraph -Scopes "AuditLog.Read.All","Mail.Send"
$StartDate = (Get-Date).AddDays(-$LookbackDays).ToString("yyyy-MM-ddTHH:mm:ssZ")
$SignInLogs = Get-MgAuditLogSignIn -All -Filter "createdDateTime ge $StartDate" `
-Property Id,UserDisplayName,UserPrincipalName,AppDisplayName,IpAddress,Location,Status,CreatedDateTime,ConditionalAccessStatus,ClientAppUsed,ResourceDisplayName
$ReportRows = $SignInLogs | Select-Object `
@{n='UserDisplayName'; e={$_.UserDisplayName}},
@{n='UserPrincipalName'; e={$_.UserPrincipalName}},
@{n='AppDisplayName'; e={$_.AppDisplayName}},
@{n='ResourceDisplayName'; e={$_.ResourceDisplayName}},
@{n='IPAddress'; e={$_.IpAddress}},
@{n='Location'; e={
if ($_.Location.city) {
"$($_.Location.city), $($_.Location.countryOrRegion)"
} else {
"Unknown"
}
}},
@{n='LoginResult'; e={
if ($_.Status.errorCode -eq 0) {
"Success"
} else {
"Failed ($($_.Status.failureReason))"
}
}},
@{n='ConditionalAccess'; e={$_.ConditionalAccessStatus}},
@{n='ClientAppUsed'; e={$_.ClientAppUsed}},
@{n='Timestamp(UTC)'; e={[datetime]$_.CreatedDateTime}}
$ReportPath = "$env:TEMP\UserLoginReport_Last${LookbackDays}Days.csv"
$ReportRows |
Sort-Object 'Timestamp(UTC)' -Descending |
Export-Csv -Path $ReportPath -NoTypeInformation -Encoding UTF8
$loginCount = @($ReportRows).Count
$Subject = "User Login Report (Past $LookbackDays Days) β $(Get-Date -Format 'yyyy-MM-dd')"
$Body = @"
Hello Admin,<br><br>
Attached is the <b>User Login Report</b> generated from Entra ID (Azure AD) Sign-In Logs.<br>
Total sign-in records: <b>$loginCount</b><br><br>
Each record includes:<br>
- User Display Name<br>
- UPN<br>
- Application Accessed<br>
- IP Address & Location<br>
- Login Result (Success/Failure)<br>
- Conditional Access Status<br><br>
Regards,<br>
Graph PowerShell Script
"@
$AttachmentContent = [System.Convert]::ToBase64String([System.IO.File]::ReadAllBytes($ReportPath))
$Attachments = @(
@{
"@odata.type" = "#microsoft.graph.fileAttachment"
Name = [System.IO.Path]::GetFileName($ReportPath)
ContentBytes = $AttachmentContent
}
)
$Message = @{
Message = @{
Subject = $Subject
Body = @{
ContentType = "HTML"
Content = $Body
}
ToRecipients = @(
@{ EmailAddress = @{ Address = $AdminUPN } }
)
Attachments = $Attachments
}
SaveToSentItems = "true"
}
Send-MgUserMail -UserId $AdminUPN -BodyParameter $Message
Write-Host "User login report (last $LookbackDays days) emailed successfully to $AdminUPN"
| Error | Cause | Solution |
|---|---|---|
| Insufficient privileges to complete the operation | Missing required Graph permissions | Connect using AuditLog.Read.All and Mail.Send scopes. |
| Invalid filter clause: The DateTimeOffset text... | The filter date format is invalid. | Use the proper UTC format: ToString("yyyy-MM-ddTHH:mm:ssZ"). |
| Send-MgUserMail : Resource not found | Invalid or non-mail-enabled account in $AdminUPN. | Use a valid mailbox-enabled administrator account. |
| Empty CSV File | No sign-ins occurred during the defined period. | Increase $LookbackDays or confirm that sign-in logging is enabled in Entra ID. |
This Graph PowerShell script offers an efficient way to monitor user sign-ins in your Microsoft 365 tenant. It captures essential details such as login results, IP address, and conditional access status, providing valuable visibility into authentication patterns.
By automating this process, administrators can easily track suspicious login activity, identify failed attempts, and maintain compliance through periodic login reports. With small tweaks β such as adding MFA insights or failure alerts β this script can become a core part of your security and compliance monitoring toolkit
© m365corner.com. All Rights Reserved. Design by HTML Codex