Track M365 Users Demoted From Admin Roles Using Graph PowerShell

Monitoring changes in administrative privileges is a critical aspect of security management in Azure AD. Keeping track of users who were recently demoted from admin roles ensures that you can verify who lost elevated access and why. In this article, we’ll explore how to use Microsoft Graph PowerShell to track users who were removed from administrative roles. This script provides a quick and easy way to monitor role changes and verify the results of these actions.

The Script

# Define the time range for recent role removals (e.g. past 7 days)
$startDate = (Get-Date).AddDays(-7).ToString("yyyy-MM-ddTHH:mm:ssZ")

# Fetch audit logs for directory role removals in the given time range
$logs = Get-MgAuditLogDirectoryAudit -Filter "activityDateTime ge $startDate and activityDisplayName eq 'Remove member from role'" -All

# Initialize an array to store the results
$results = @()

# Loop through the audit logs and extract the required information
foreach ($log in $logs) {
    $removedTime = $log.ActivityDateTime
    $roleRemovedFrom = $log.TargetResources | Where-Object { $_.Type -eq 'User' } | Select-Object -ExpandProperty UserPrincipalName
    $removedBy = $log.InitiatedBy.User.UserPrincipalName
    $status = $log.Result

    # Create a custom object to store the data
    $result = [pscustomobject]@{
        "Removed Time"         = $removedTime
        "Role Removed From"    = $roleRemovedFrom
        "Removed By"           = $removedBy
        "Result Status"        = $status
    }

    # Add the result to the results array
    $results += $result
}

# Display the results in a table format
$results | Format-Table -AutoSize

How the Script Works?

  • Time Range: The script begins by defining a time range for the audit log search (in this case, the past 7 days). You can easily modify this range by adjusting the AddDays(-7) function.
  • Audit Log Query: The Get-MgAuditLogDirectoryAudit cmdlet fetches logs related to Azure AD role removals. It filters for actions where members were removed from roles using the activity name 'Remove member from role'.
  • Extracting Data: For each log entry, the script extracts key details:
    • Removed Time: The date and time when the role was removed.
    • Role Removed From: The user who was removed from the role (email).
    • Removed By: The admin who performed the removal action (email).
    • Result Status: Whether the removal was successful or failed.
  • Output: The results are displayed in a clean tabular format providing a quick overview of recent demotions from administrative roles.

Further Enhancements

  • Include Role Name: You can extend the script to display the name of the role from which the user was removed by querying the ModifiedProperties field or looking up the role information using the role’s ID.
  • Custom Date Range: Instead of hardcoding the 7-day time frame, modify the script to accept user input for a custom date range.
  • Email Notifications: Set up the script to automatically email a report to administrators whenever users are demoted from critical roles.
  • Export to CSV: You can export the results to a CSV file for easy reporting:
  • $results | Export-Csv -Path "C:\DemotedAdmins.csv" -NoTypeInformation

Possible Errors & Solutions

Insufficient Permissions

Cause: Ensure that the account running the script has the necessary permissions to query Azure AD audit logs. You’ll need at least the AuditLog.Read.All permission in Microsoft Graph.

Audit Log Not Enabled

Cause: If the Get-MgAuditLogDirectoryAudit cmdlet returns no data, check whether auditing is enabled in your Azure AD tenant. Without auditing, you won’t be able to retrieve role changes.

API Throttling

Cause: If you’re querying large datasets, you might encounter throttling from Microsoft Graph.

Solution: To avoid this, reduce the date range or implement paging by using the -Top and -Skip parameters to limit the number of results returned per query.

Conclusion

Monitoring changes to administrative privileges is essential for maintaining security and compliance in Azure AD. This PowerShell script provides a simple way to track users who were recently demoted from admin roles, allowing you to stay on top of role changes and verify that they were executed successfully. By further enhancing the script with additional features like role names, custom date ranges, and automatic notifications, you can tailor it to meet your organization’s auditing needs.

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