I added a bunch of users to one of my groups by mistake and need to remove them. I know they were added in the last few weeks, so I figured using the audit logs to identify these would be the best approach.
When users are added to a group the “Add member to group” event is generated. So I can use the following to get all such events:
1 |
Get-MgAuditLogDirectoryAudit -filter "activityDisplayName eq 'Add member to group'" |
I don’t want every single group, just mine.
An example entry from the output of the above looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
ActivityDateTime : 01/01/2024 09:17:05 ActivityDisplayName : Add member to group AdditionalDetails : {} Category : GroupManagement CorrelationId : 4b8c1203-f132-4edb-ba75-f3fc45d7829d Id : Directory_2b8c1203-e132-4edb-ba73-f3fc45d7829d_VQMGX_226414768 InitiatedBy : Microsoft.Graph.PowerShell.Models.MicrosoftGraphAuditActivityInitiator LoggedByService : Core Directory OperationType : Assign Result : success ResultReason : TargetResources : {a106b3d1-58fd-4124-b553-237bf7338909, 24461b6b-5491-4f14-b7a0-64cd1f1411af} AdditionalProperties : {} |
The TargetResources
have the info we need.
1 2 3 4 |
DisplayName GroupType Id Type UserPrincipalName ----------- --------- -- ---- ----------------- 1206b3d1-58fd-4124-b253-237bf7338909 User axxx@dot.com unknownFutureValue a3451b6b-5491-4f14-b7a1-64cd1f1411af Group |
So I must filter for the group by its Id.
1 2 3 |
$groupId = 'xxxx' Get-MgAuditLogDirectoryAudit -filter "(activityDisplayName eq 'Add member to group' and targetResources/any(t:t/Id eq '$groupId'))" |
And then to get just the user Ids I can do:
1 2 3 4 |
$groupId = 'xxxx' Get-MgAuditLogDirectoryAudit -filter "(activityDisplayName eq 'Add member to group' and targetResources/any(t:t/Id eq '$groupId'))" | ForEach-Object { $_.TargetResources | Where-Object { $_.Type -eq "User"} | Select-Object Id } |
And finally, to remove these users:
1 2 3 4 5 |
$groupId = 'xxxx' Get-MgAuditLogDirectoryAudit -filter "(activityDisplayName eq 'Add member to group' and targetResources/any(t:t/Id eq '$groupId'))" | ForEach-Object { $_.TargetResources | Where-Object { $_.Type -eq "User"} } | ForEach-Object { Remove-MgGroupMemberByRef -GroupId $groupId -DirectoryObjectId $_.Id } |
That’s it!