Microsoft 365 administrators often need to track user creation activity for compliance, audit, or security purposes. Whether it's identifying who created a user or validating if the action was successful, Directory Audit Logs can help.
This article walks through a Graph PowerShell script that fetches all “Add User” events from the User Management audit category and displays the following details:
# Connect to Microsoft Graph with AuditLog permissions
Connect-MgGraph -Scopes "AuditLog.Read.All"
# Set the filter parameters
$category = "UserManagement"
$activity = "Add user"
$startDate = (Get-Date).AddDays(-30).ToString("yyyy-MM-ddTHH:mm:ssZ") # Adjust as needed
# Query the directory audit logs
$logs = Get-MgAuditLogDirectoryAudit -All `
-Filter "category eq '$category' and activityDisplayName eq '$activity' and activityDateTime ge $startDate" `
-Property activityDateTime, initiatedBy, targetResources, result, category, activityDisplayName
# Format the output
$results = foreach ($log in $logs) {
$createdUser = $log.targetResources | Where-Object { $_.type -eq "User" } | Select-Object -First 1
[PSCustomObject]@{
'Created Time' = $log.activityDateTime
'Created User' = $createdUser.userPrincipalName
'Created By' = $log.initiatedBy.user.userPrincipalName
'Result Status'= $log.result
}
}
# Display the results
$results | Format-Table -AutoSize
Here’s how this script operates behind the scenes:
You can enhance this script to meet additional audit needs:
$results | Export-Csv -Path "AddUserAuditLog.csv" -NoTypeInformation
$results | Where-Object { $_.'Created By' -eq "admin@domain.com" }
$startDate = (Get-Date).AddDays(-90).ToString("yyyy-MM-ddTHH:mm:ssZ")
Highlight and notify about failures in user creation:
$failures = $results | Where-Object { $_.'Result Status' -ne "success" }
Error | Cause | Solution |
Access Denied | Missing permissions | Ensure you’ve consented to AuditLog.Read.All |
Property not found | Incorrect property name | Ensure property names like activityDisplayName, initiatedBy, and targetResources are correct |
No output returned | No logs match criteria | Extend $startDate or verify if users were added in the timeframe |
Unauthorized | Not logged in | Run Connect-MgGraph before executing the script |
Tracking user creation activity using audit logs is crucial for maintaining transparency and accountability in Microsoft 365 environments. With Graph PowerShell, admins can automate this tracking and even build on top of the script to generate alerts, reports, or integrate with ticketing systems.
If you’re looking to bolster your compliance monitoring or simplify admin investigations, this script provides a powerful, extensible foundation.
© m365corner.com. All Rights Reserved. Design by HTML Codex