Retrieve M365 Deleted Users List Using Graph PowerShell

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.

The Script

# 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

How the Script Works

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:

  • Authentication: The script begins by importing the Microsoft Graph PowerShell module and authenticating with Connect-MgGraph. It requires the AuditLog.Read.All scope, which allows it to read audit logs.
  • Date Range Definition: The script defines a date range to query recently deleted users. In this example, it checks for users deleted in the past 30 days, but you can adjust the time period by modifying the $startDateTime variable.
  • Fetching Audit Logs: Using the Get-MgAuditLogDirectoryAudit cmdlet, the script retrieves all audit logs within the defined date range. The query uses a filter on the activityDateTime field, ensuring that only logs from the specified time range are returned.
  • Filtering Deleted User Events: Inside the loop, the script checks each audit log event to see if the ActivityDisplayName is "Delete User." If it finds such an event, it extracts the relevant details, including the deletion time, the deleted user’s email, the admin who performed the deletion, and the result status (Success or Failed).
  • Displaying the Results: The extracted data is stored in a custom object and displayed in a tabular format using Format-Table. If no deleted users are found, the script informs the user.

Further Enhancing the Script

This basic script can be enhanced to provide more functionality and flexibility:

  • Custom Date Input: Allow administrators to input their own date range when running the script, making it more dynamic.
  • Export Results to CSV: Export the results to a CSV file for record-keeping or sharing with other team members.
  • Automated Email Notifications: Automate sending email reports of deleted users using the Send-MailMessage cmdlet for periodic monitoring.

Possible Errors & Solutions

Error 1: Authentication Error

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 2: No Results Returned

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 3: Invalid Date Format

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 4: UserPrincipalName Not Found

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.

Conclusion

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