Track “Delete User” Events Using Graph PowerShell – Audit Log Script

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:

  • 🕒 Deleted Time
  • 👤 Deleted User (UPN)
  • 🧑‍💼 Deleted By (Initiator UPN)
  • ✅ Result Status (Success or Failure)

The Script: Fetch “Delete User” Events from Directory Audit Logs

# 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
                                

How the Script Works

  1. Connect-MgGraph: Establishes a connection to Microsoft Graph with the required AuditLog.Read.All permission.
  2. Filter Setup: Filters the audit logs to include only events categorized under UserManagement with an activityDisplayName of “Delete user”.
  3. Date Range: The script looks back 30 days from the current date. You can modify this using the $startDate variable.
  4. Log Processing: The script loops through each audit log entry and extracts:
    • Deleted Time → When the deletion occurred
    • Deleted User → The UPN of the deleted user
    • Deleted By → The initiator’s UPN
    • Result Status → Whether the action was successful or not
  5. Output: The details are formatted into a clean table view.

Further Enhancing the Script

You can customize or expand the script to suit your operational or compliance needs:

  1. Change Audit Time Range
  2. $startDate = (Get-Date).AddDays(-90).ToString("yyyy-MM-ddTHH:mm:ssZ")
  3. Export to CSV
  4. $results | Export-Csv -Path "DeletedUserAuditLog.csv" -NoTypeInformation
  5. Filter Specific Initiators (Admins or Users)
  6. $results | Where-Object { $_.'Deleted By' -eq "admin@domain.com" }
  7. Alert for Failures
  8. $failures = $results | Where-Object { $_.'Result Status' -ne "success" }

Possible Errors & Solutions

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

Conclusion

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


Graph PowerShell Explorer Widget

20 Graph PowerShell cmdlets with easily accessible "working" examples.


Permission Required

Example:


                


                


                

© m365corner.com. All Rights Reserved. Design by HTML Codex