In any organization, user deletion is a sensitive and critical action that administrators must keep a close eye on. Whether a user leaves the company or an account is removed accidentally, it’s important to have a record of the deleted user, the time they were deleted, and who initiated the deletion. Using Microsoft Graph PowerShell, administrators can easily query Azure Active Directory (Azure AD) to fetch recently deleted user details. In this article, we’ll explore how to use a PowerShell script to retrieve key details about deleted users, including the time of deletion, the user’s email, the admin who performed the action, and the result status.
# Import the Microsoft Graph PowerShell module
Import-Module Microsoft.Graph
# Authenticate and connect to Microsoft Graph
Connect-MgGraph -Scopes "AuditLog.Read.All"
# Define the date range for fetching deleted users (customize as needed)
$startDateTime = (Get-Date).AddDays(-30).ToString("yyyy-MM-ddTHH:mm:ssZ") # Past 30 days
# Fetch all DirectoryAudit logs in the past 30 days (without filter for 'Delete User')
$allAuditLogs = Get-MgAuditLogDirectoryAudit -Filter "activityDateTime ge $startDateTime"
# Create an array to store the formatted results
$deletedUserDetails = @()
# Loop through the audit logs to find 'Delete User' events
foreach ($event in $allAuditLogs) {
if ($event.ActivityDisplayName -eq 'Delete User') {
$deletedTime = $event.ActivityDateTime
$deletedUser = ($event.TargetResources | Where-Object { $_.UserPrincipalName }).UserPrincipalName
$deletedBy = $event.InitiatedBy.User.UserPrincipalName
$resultStatus = if ($event.Result -eq 'success') { 'Success' } else { 'Failed' }
# Create an object for each record
$userDetail = [pscustomobject]@{
"Deleted Time" = $deletedTime
"Deleted User" = $deletedUser
"Deleted By" = $deletedBy
"Result Status" = $resultStatus
}
# Add the object to the results array
$deletedUserDetails += $userDetail
}
}
# Output the results in a tabular format
if ($deletedUserDetails.Count -eq 0) {
Write-Host "No deleted user events found in the given date range."
} else {
$deletedUserDetails | Format-Table -AutoSize
This PowerShell script helps you track recently deleted users in Azure AD by leveraging Microsoft Graph audit logs. Here’s a breakdown of how the script functions:
This basic script can be enhanced to provide more functionality and flexibility:
Error: "Insufficient privileges to complete the operation."
Cause: The account used does not have the AuditLog.Read.All permission.
Solution: Grant the required permission to the account and re-authenticate using Connect-MgGraph.
Error: "No deleted user events found in the given date range."
Cause: Either no users were deleted in the specified time range or the filtering criteria are too narrow.
Solution: Adjust the date range or broaden the filter criteria to ensure that all relevant events are captured.
Error: "Invalid DateTime format"
Cause: The date format for the activityDateTime filter must follow the ISO 8601 standard (yyyy-MM-ddTHH:mm:ssZ).
Solution: Ensure that the date format used is correct.
Error: "Cannot find UserPrincipalName in TargetResources"
Cause: The TargetResources property may not always contain UserPrincipalName.
Solution: Add error handling to check if the UserPrincipalName exists and handle missing values gracefully.
Monitoring deleted users in Azure AD is essential for maintaining security and auditing within your organization. With this PowerShell script, you can easily track when a user was deleted, who performed the deletion, and whether the action was successful. By leveraging Microsoft Graph’s audit logs, you gain valuable insights into user account management and can enhance transparency in administrative actions.
This script can be further customized and enhanced to fit specific organizational needs, whether for reporting, alerting, or exporting data. By automating these tasks, administrators can stay on top of critical account management operations with ease.
© m365corner.com. All Rights Reserved. Design by HTML Codex