Keeping track of administrative actions in Microsoft 365 is crucial for maintaining security and compliance. One such important action is user restoration where administrators restore deleted user accounts. This article provides a PowerShell script to track which admins performed user restoration activities within the last 30 days using the Microsoft Graph PowerShell module.
Here is the PowerShell script to fetch and display the list of admins who performed user restoration activities in the past 30 days:
# Ensure the Microsoft.Graph module is installed and imported
Install-Module -Name Microsoft.Graph -Force -AllowClobber
Import-Module Microsoft.Graph
# Connect to Microsoft Graph
Connect-MgGraph -Scopes "AuditLog.Read.All"
# Calculate the date 30 days ago from today
$DateThreshold = (Get-Date).AddDays(-30).ToString("yyyy-MM-ddTHH:mm:ssZ")
# Fetch directory audit logs for user restoration activities
$AuditLogs = Get-MgAuditLogDirectoryAudit -Filter "activityDisplayName eq 'Restore user' and activityDateTime ge $DateThreshold"
# Extract and display relevant information
$AuditLogs | ForEach-Object {
$targetResource = $_.TargetResources | Where-Object { $_.Type -eq 'User' }
[PSCustomObject]@{
ActivityDisplayName = $_.ActivityDisplayName
ActivityDateTime = $_.ActivityDateTime
AdminDisplayName = $_.InitiatedBy.User.DisplayName
AdminUserPrincipalName = $_.InitiatedBy.User.UserPrincipalName
TargetUserPrincipalName = $targetResource.UserPrincipalName
}
} | Format-Table -AutoSize
Script Output
Ensures the Microsoft.Graph module is installed and imported enabling interaction with the Microsoft Graph API through PowerShell.
Uses Connect-MgGraph to authenticate and establish a connection to the Microsoft Graph API with the required permissions to read audit logs.
Computes the date 30 days ago from the current date in the required format using Get-Date and AddDays(-30).
Uses Get-MgAuditLogDirectoryAudit to fetch directory audit logs with the activityDisplayName of 'Restore user' and an activityDateTime within the last 30 days.
Iterates through each audit log entry to extract and display the relevant information including:
Connect-MgGraph : Exception of type 'Microsoft.Graph.Auth.AuthException' was thrown.
Solution:
Get-MgAuditLogDirectoryAudit : Invalid filter clause.
Solution:
Too many requests error.
Solution:
Tracking administrative actions such as user restoration in Microsoft 365 is essential for maintaining security and compliance. Using the Microsoft Graph PowerShell module, administrators can efficiently monitor and report on these activities. This script provides a straightforward solution to track which admins restored users within the last 30 days, helping organizations ensure accountability and transparency in their administrative actions.
© m365corner.com. All Rights Reserved. Design by HTML Codex