2

What is the fastest way to remove all users from an Azure AD group in PowerShell? I am currently using

$deleteThem = Get-MsolGroupMember -GroupObjectId $groupId -All 
foreach ($user in $deleteThem) {
    Remove-MsolGroupMember -GroupObjectId $groupId -GroupMemberObjectId $user.ObjectId
}

but this is painfully slow. I need to retain the group and group id though. Any ideas?

Vitamin X
  • 21
  • 1
  • 2
  • 1
    I think there aren't many other ways than what you're doing right now. The AzureAD module _might be_ faster since its newer but can't tell for sure. – Santiago Squarzon Jul 14 '21 at 12:43
  • Maybe `Get-MsolGroupMember -GroupObjectId $groupId -All | Remove-MsolGroupMember -GroupMemberObjectId $_.ObjectID`? – Abraham Zinala Jul 14 '21 at 12:55
  • Use [Remove-AzADGroupMember](https://learn.microsoft.com/en-us/powershell/module/az.resources/remove-azadgroupmember?view=azps-6.2.1), because `MemberObjectID` accepts an array. `$Users = Get-AzADGroupMember -GroupObjectID ; Remove-AzADGroupMember -GroupDisplayName -MemberObjectId $Users.Id`. – Ash Jul 14 '21 at 13:20
  • Thanks for the suggestion, @Ash. Alas, it's only marginally faster (4min 5secs compared to 4min 30secs for ~1300 users). Guess I have to settle with it :) – Vitamin X Jul 15 '21 at 17:37
  • I would imagine that all of these modules are built from AutoRest, and that they are just making a Microsoft Graph call and then the backend has to process all the changes. You could look at doing it via the Azure/Graph REST APIs yourself to see if there is any significant difference, but I doubt it. – Ash Jul 15 '21 at 18:25

1 Answers1

1

As mentioned by Ash in comments section , Using Remove-AzADGroupMember is faster than Remove-MsolGroupMember.

I ran the below script for deleting users in a group by just providing the Group name.

Import-Module AzureAD
$Credential = Get-Credential
Connect-AzureAD -Credential $Credential
$group=Get-AzureADGroup -SearchString 'Your Tenant Group Name' 
$users=Get-AzureADGroupMember -ObjectId $Group.ObjectId -All $true |where {$_.ObjectType -eq 'User'}
foreach($user in $users){
Remove-AzureADGroupMember -ObjectId $Group.ObjectId -MemberId $user.objectId
} 

enter image description here

Note : In credentials prompt box, provide the admin id of the tenant and password. If there are lot of users in the group then it is expected to take some time.

Ansuman Bal
  • 9,705
  • 2
  • 10
  • 27