Tracking user deletion events in Microsoft 365 is crucial for ensuring security, accountability, and compliance in your organization. Whether it’s for audit reviews or identifying accidental deletions, Microsoft Graph PowerShell allows administrators to query detailed audit logs with ease.
This article walks you through a script that pulls “Delete User” events from the UserManagement audit category and provides a detailed view of:
# Connect to Microsoft Graph with AuditLog permissions
Connect-MgGraph -Scopes "AuditLog.Read.All"
# Define filter parameters
$category = "UserManagement"
$activity = "Delete user"
$startDate = (Get-Date).AddDays(-30).ToString("yyyy-MM-ddTHH:mm:ssZ") # Change as needed
# Query audit logs for Delete user events
$logs = Get-MgAuditLogDirectoryAudit -All `
-Filter "category eq '$category' and activityDisplayName eq '$activity' and activityDateTime ge $startDate" `
-Property activityDateTime, initiatedBy, targetResources, result
# Format output
$results = foreach ($log in $logs) {
$deletedUser = $log.targetResources | Where-Object { $_.type -eq "User" } | Select-Object -First 1
[PSCustomObject]@{
'Deleted Time' = $log.activityDateTime
'Deleted User' = $deletedUser.userPrincipalName
'Deleted By' = $log.initiatedBy.user.userPrincipalName
'Result Status' = $log.result
}
}
# Display results
$results | Format-Table -AutoSize
You can customize or expand the script to suit your operational or compliance needs:
$startDate = (Get-Date).AddDays(-90).ToString("yyyy-MM-ddTHH:mm:ssZ")
$results | Export-Csv -Path "DeletedUserAuditLog.csv" -NoTypeInformation
$results | Where-Object { $_.'Deleted By' -eq "admin@domain.com" }
$failures = $results | Where-Object { $_.'Result Status' -ne "success" }
Error | Cause | Solution |
Access Denied | Missing permissions | Ensure AuditLog.Read.All is granted and consented |
No logs returned | No matching events in date range | Adjust $startDate or verify deletion activity occurred |
Unauthorized (401) | Not connected to Graph | Run Connect-MgGraph before executing the script |
Property not found | Property names changed | Verify property names such as initiatedBy, targetResources from API |
Monitoring “Delete User” activity in Microsoft 365 is essential for safeguarding your directory and preventing unauthorized account removals. This Graph PowerShell script provides a quick and reliable way to surface critical audit events, identify who performed the deletion, and ensure every action was successful.
You can plug this script into reporting workflows, alerting systems, or automate it via scheduled tasks to bolster your tenant’s audit trail
© m365corner.com. All Rights Reserved. Design by HTML Codex