Track Users Added to Microsoft 365 Groups with Graph PowerShell

In Microsoft 365, managing and auditing group memberships is crucial for security and compliance. This article presents a PowerShell script that tracks when users were added to Microsoft 365 groups and by whom. By leveraging the Microsoft Graph API, this script fetches audit logs for ‘user-added-to-group’ events and displays the relevant details in the console.


PowerShell Script

Below is the PowerShell script that fetches and displays the ‘user-added-to-group’ events for the past 30 days:

# Function to get the start time (default to 30 days ago)
function Get-StartTime {
    return (Get-Date).AddDays(-30).ToUniversalTime()
}

# Function to track user added to group events
function Track-UserAddedToGroupEvent {
    $startTime = Get-StartTime
    $endTime = (Get-Date).ToUniversalTime()

    # Convert datetime to the required format
    $startTimeFormatted = $startTime.ToString("yyyy-MM-ddTHH:mm:ssZ")
    $endTimeFormatted = $endTime.ToString("yyyy-MM-ddTHH:mm:ssZ")

    try {
        # Fetch directory audit logs for the past 30 days
        $auditLogs = Get-MgAuditLogDirectoryAudit -Filter "activityDateTime ge $startTimeFormatted and activityDateTime le $endTimeFormatted"
        
        # Filter for user added to group events
        $userAddedToGroupEvents = $auditLogs | Where-Object { $_.activityDisplayName -eq "Add member to group" }

        # Display the results in the console
        foreach ($event in $userAddedToGroupEvents) {
            $userDetails = $event.targetResources | Where-Object { $_.userPrincipalName }
            $adminDetails = $event.initiatedBy.user | Select-Object userPrincipalName displayName

            Write-Output "DateTime: $($event.activityDateTime)"
            Write-Output "User Added: $($userDetails.userPrincipalName)"
            Write-Output "Added By (Admin): $($adminDetails.userPrincipalName)"
            Write-Output "Admin DisplayName: $($adminDetails.displayName)"
            Write-Output "----------------------------------------"
        }
    } catch {
        Write-Output "Error fetching audit logs: $_"
    }
}

# Run the function
Track-UserAddedToGroupEvent

Script Output


Script Explanation

Get-StartTime Function:

This function returns the date and time from 30 days ago in UTC format. It is used to set the start time for fetching the audit logs.

Track-UserAddedToGroupEvent Function:

This function defines the time range (past 30 days) and converts it to the required format. It fetches the directory audit logs using the Get-MgAuditLogDirectoryAudit cmdlet with a filter for the defined time range. It filters the logs to find the ‘user is added to a group’ event. It extracts the user details and admin details from each relevant event and displays them in the console.

Error Handling:

The script includes a try-catch block to handle any errors that occur during the fetching of audit logs, ensuring that any issues are logged for further troubleshooting.


Further Enhancements

  • Logging to File: Instead of displaying the results in the console, you can log them to a file for persistent tracking and auditing. Modify the Write-Output commands to Add-Content to write the logs to a file.
  • Email Notifications: You can extend the script to send email notifications whenever a user is added to a group. Use the Send-MailMessage cmdlet to send the log details via email.
  • Scheduled Task: Automate the script to run at regular intervals using Task Scheduler. Schedule the script to run daily or weekly to ensure continuous monitoring.

Possible Errors & Solutions

Invalid Filter Clause Error:

Error: "Invalid filter clause: An identifier was expected at position X."

Solution: Ensure the datetime values are correctly formatted and enclosed in quotes. The correct format is yyyy-MM-ddTHH:mm:ssZ.

Permission Issues:

Error: "Insufficient privileges to complete the operation."

Solution: Ensure the account running the script has the necessary permissions to access audit logs in Microsoft 365. "AuditLog.Read.All" is the required Graph API permission.

Network or API Throttling:

Error: "Rate limit exceeded" or "Network error."

Solution: Implement retry logic in the script to handle temporary network issues or API throttling by Microsoft Graph.


Conclusion

Tracking users added to Microsoft 365 groups is vital for maintaining security and compliance within your organization. By leveraging the Microsoft Graph API and PowerShell, you can automate this process and gain valuable insights into group membership changes. The provided script is a starting point, and you can enhance it further to meet your specific requirements, such as logging to files, sending email notifications, and automating execution through scheduled tasks.


Related Articles:

Using Get-MgDirectoryRole in Graph PowerShell
Using Get-MgUserLicenseDetail in Graph PowerShell
Using Find-GraphMgCommand in Graph PowerShell
Connect to Microsoft 365 Using PowerShell
How to Create Bulk Users in Office 365 Using Graph PowerShell?
Create Microsoft 365 Group Using Microsoft Graph PowerShell
Block Microsoft 365 User Using Microsoft Graph PowerShell
Assign Microsoft 365 License Using Graph PowerShell
Microsoft 365 User Management Using Graph PowerShell
Checking Group Membership in Microsoft 365
Bulk Assign Microsoft 365 License
Find Inactive Users in Microsoft 365
Using Powershell Graph Search Query
Using Powershell Graph Filter Query
Using Where-Object In Graph PowerShell
Using Expand Property In Graph PowerShell
Using Select Object In Graph PowerShell
Using -Contains Operator In Graph PowerShell
Add User to Multiple Microsoft 365 Groups Using Graph PowerShell
Get Microsoft 365 User Location Using Graph PowerShell
Import Microsoft 365 Groups from CSV File Using Graph PowerShell
Microsoft 365 Group User Import Using Graph PowerShell

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