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.
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
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.
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.
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.
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.
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.
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.
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.
© m365corner.com. All Rights Reserved. Design by HTML Codex