Retrieve M365 Restored Users List Using Graph PowerShell

In Azure Active Directory (Azure AD), user restoration is a critical operation, especially when accidental deletions occur. Administrators need to keep track of when a user is restored, by whom, and whether the restoration was successful. With Microsoft Graph PowerShell, you can easily query the Azure AD audit logs to retrieve detailed information about restored users.

In this article, we’ll explore a PowerShell script that helps you fetch such details, including the restored time, user email, admin email, and result status in a tabular format.


The Script: Retrieve M365 Restored Users List


    # 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 restored 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 'Restore User')
    $allAuditLogs = Get-MgAuditLogDirectoryAudit -Filter "activityDateTime ge $startDateTime"

    # Create an array to store the formatted results
    $restoredUserDetails = @()

    # Loop through the audit logs to find 'Restore User' events
    foreach ($event in $allAuditLogs) {
        if ($event.ActivityDisplayName -eq 'Restore User') {
            $restoredTime = $event.ActivityDateTime
            $restoredUser = ($event.TargetResources | Where-Object { $_.UserPrincipalName }).UserPrincipalName
            $restoredBy = $event.InitiatedBy.User.UserPrincipalName
            $resultStatus = if ($event.Result -eq 'success') { 'Success' } else { 'Failed' }

            # Create an object for each record
            $userDetail = [pscustomobject]@{
            "Restored Time"  = $restoredTime
            "Restored User"  = $restoredUser
            "Restored By"    = $restoredBy
            "Result Status"  = $resultStatus
            }

            # Add the object to the results array
            $restoredUserDetails += $userDetail
        }
    }

    # Output the results in a tabular format
    if ($restoredUserDetails.Count -eq 0) {
        Write-Host "No restored user events found in the given date range."
    } else {
        $restoredUserDetails | Format-Table -AutoSize
    }

How the Script Works

The PowerShell script uses Microsoft Graph PowerShell to retrieve audit logs that record user restoration events. Here's how the script operates:

  • Authentication: The script starts by importing the Microsoft Graph PowerShell module and connecting to the Graph API with the necessary scope (AuditLog.Read.All) to read audit logs.
  • Defining Date Range: We define the start date for the audit log query. In this case, it retrieves events from the last 30 days.
  • Retrieving Logs: Using Get-MgAuditLogDirectoryAudit, the script retrieves all audit logs within the specified date range.
  • Filtering Events: The script loops through the audit logs and checks the ActivityDisplayName field for "Restore User" events, identifying user restoration activities.
  • Extracting Information: For each restoration event, details such as restored time (ActivityDateTime), the restored user's email, the admin who restored the user, and the result status (success or failed) are extracted.
  • Displaying Results:The script stores this information in a custom object and outputs it in a table format.

Further Enhancing the Script

This basic script can be expanded with additional features to suit different administrative needs:

  • Custom Date Range: Modify the script to accept custom date ranges as user input, allowing administrators to specify the time period they want to query.
  • Export to CSV: You can easily export the results to a CSV file using Export-Csv to keep a record of restored user events for future reference.
  • $restoredUserDetails | Export-Csv -Path "RestoredUsers.csv" -NoTypeInformation
  • Email Notifications: Automatically send an email with the report once the script completes execution. This could be integrated with Office 365's Send-MailMessage cmdlet for periodic reports.

Possible Errors & Solutions

Here are some common errors you might encounter while running this script and how to resolve them:

Authentication Issues

Error: "Insufficient privileges to complete the operation."

Cause: The account used for authentication does not have the AuditLog.Read.All permission

Solution: Ensure that the account has the necessary permissions by granting the AuditLog.Read.All role in Azure AD and re-authenticate using Connect-MgGraph.

No Results Returned

Error: "No restored user events found in the given date range."

Cause: Either there were no restoration events in the specified period, or the filter criteria are too restrictive.

Solution: Adjust the date range or broaden the filter criteria to ensure the script captures all relevant events.

Invalid Date Format

Error: "Invalid DateTime format"

Cause: : Date formatting in the OData filter might be incorrect.

Solution: Ensure the date is in the correct format (yyyy-MM-ddTHH:mm:ssZ) as shown in the script.


Conclusion

Tracking restored users in Azure AD is a crucial aspect of auditing and compliance. With this PowerShell script, you can easily query audit logs to retrieve important details about restored users and the administrators who performed the action. The script can be customized and enhanced further to suit your organization's specific needs, whether for reporting, notifications, or archiving purposes.


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