Monitoring user-related events in Microsoft 365 is a critical part of maintaining security, compliance, and operational transparency. Whether you're tracking user creations, updates, deletions, or role changes, the Azure AD audit logs contain all the information you need. This article walks you through a Graph PowerShell script that fetches all user-related events and displays meaningful insights in your console.
Here’s a Graph PowerShell script that fetches all Azure AD audit log entries where actions were performed on user accounts. It displays:
# Connect to Microsoft Graph
Connect-MgGraph -Scopes "AuditLog.Read.All"
# Define timeframe (e.g., past 30 days)
$startDateTime = (Get-Date).AddDays(-30).ToString("yyyy-MM-ddTHH:mm:ssZ")
# Fetch all audit logs from the last 30 days
$allAuditLogs = Get-MgAuditLogDirectoryAudit -Filter "activityDateTime ge $startDateTime" -All
# Filter for logs where the target resource has a UserPrincipalName (indicating it's a user-related action)
$userEvents = @()
foreach ($log in $allAuditLogs) {
$userTarget = $log.TargetResources | Where-Object { $_.UserPrincipalName }
if ($userTarget) {
$userEvents += [pscustomobject]@{
"Event Time" = $log.ActivityDateTime
"Operation" = $log.ActivityDisplayName
"Actor" = $log.InitiatedBy.User.UserPrincipalName
"Target" = $userTarget.UserPrincipalName
"Results" = if ($log.Result -eq 'success') { "Success" } else { "Failed" }
}
}
}
# Display results
if ($userEvents.Count -eq 0) {
Write-Host "No user-related audit events found in the last 30 days."
} else {
$userEvents | Format-Table -AutoSize
}
You can easily tweak this script to meet specific audit and reporting needs:
$userEvents | Export-Csv -Path "UserEvents.csv" -NoTypeInformation
Where-Object { $_."Operation" -eq "Delete user" }
$startDateTime = (Get-Date).AddDays(-90).ToString("yyyy-MM-ddTHH:mm:ssZ") # Last 90 days
$userEvents | Sort-Object "Event Time" -Descending | Format-Table -AutoSize
This script is helpful in many day-to-day administrative scenarios:
Error | Cause | Solution |
Access Denied | Missing required permission | Connect using Connect-MgGraph -Scopes "AuditLog.Read.All" |
The term 'Get-MgAuditLogDirectoryAudit' | Microsoft Graph module not installed | Install it using Install-Module Microsoft.Graph -Scope CurrentUser |
No results found | No user events in the date range or incorrect filters | Widen the date range or remove overly specific filters |
Whether you're preparing for a compliance check, investigating changes to user accounts, or simply improving visibility, this Graph PowerShell script gives you a clear, customizable view of all user-related events in Azure AD audit logs.
With just a few lines of PowerShell, you can enhance transparency and accountability in your Microsoft 365 environment.
Try it out, adapt it to your needs, and never lose track of user activity again!
© m365corner.com. All Rights Reserved. Design by HTML Codex