I've been trying to remove all of the groups(M365,DL,security etc.) from a user. I was trying to use this script but I'm getting errors when removing DLs(reasonably).
$Groups = Get-AzureADUserMembership -ObjectId $userID
foreach($Group in $Groups.ObjectId){
Remove-AzureADGroupMember -ObjectId $Group -MemberId $userID
}
My problem is that I have no way to get the type of the group and treat it with the correct command accordingly. When trying to use MSOL to get the type I saw that M365 groups are also being shown as a distribution list, So I'm not able to use this method.
Any advice or luck with that? Thanks!
Edit: This is how the groups are showing up, identical but not actually as it requires different command to remove the group. 365 group and DL
CodePudding user response:
I have tried with same script in my environment to remove an user from the groups and it removed successfully .
Azure portal->Groups->Enter your Group name
In my Azure Active directory ,I have Microsoft group type with 5 users:
In my Security Group type I have 4 users:
I tried with particular user like imran khan to remove from these two groups.
First you need to connect with azureAD using this command :
Import-Module AzureAD
$Credential = Get-Credential
Connect-AzureAD -Credential $Credential
Now I tried with same commands:
$userID = 'user object ID'
$Groups = Get-AzureADUserMembership -ObjectId $userID
foreach($Group in $Groups.ObjectId){
Remove-AzureADGroupMember -ObjectId $Group -MemberId $userID
}
Response:
Which returned empty that means which I removed successfully a user from the group.
Reference: Compare groups - Microsoft 365 admin | Microsoft Docs
CodePudding user response:
Considering that Azure AD group memberships can be removed via Remove-AzureAdGroupMember
while Exchange Online memberships via Remove-DistributionGroupMember
, executing both commands via a try..catch
is probably the most efficient way to meet the OP's requirements.
The code below does just that (remove the comment before the Confirm
parameter to skip confirmation.)
Connect-AzureAD
Connect-ExchangeOnline
$userid = (Get-AzureADuser -objectid "[email protected]").objectid
$Groups = Get-AzureADUserMembership -ObjectId $userID
foreach($Group in $Groups){
try {
Remove-AzureADGroupMember -ObjectId $Group.ObjectID -MemberId $userID -erroraction Stop
}
catch {
write-host "$($Group.displayname) membership cannot be removed via Azure cmdlets."
Remove-DistributionGroupMember -identity $group.mail -member $userid -BypassSecurityGroupManagerCheck # -Confirm:$false
}
}
Note: proper code formatting does help.