Remove user from manage group section in O365 portal

Rohit 0 Reputation points
2023-07-13T11:14:15.56+00:00

I'm trying this PS script but it seems user is not removed from user groups after execution.

Connect-MgGraph

Get the user by UserPrincipalName

$user = Get-MgUser -UserPrincipalName $UserPrincipalName

Get the user's group memberships

$userGroups = Get-MgUserMemberOf -UserId $user.Id | Select-Object -ExpandProperty Id

Remove the user from each group

foreach ($groupId in $userGroups) {

Remove-MgGroupMember -GroupId $groupId -MemberId $user.Id

}

Disconnect-MgGraph

Microsoft 365 and Office | Install, redeem, activate | For business | Windows
Windows for business | Windows Server | User experience | PowerShell
Microsoft Security | Microsoft Graph
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Andy David - MVP 157.8K Reputation points MVP Volunteer Moderator
    2023-07-13T11:18:46.1533333+00:00

    Hi, The correct command is:https://learn.microsoft.com/en-us/powershell/module/microsoft.graph.groups/remove-mggroupmemberbyref?view=graph-powershell-1.0

    Remove-MgGroupMemberByRef

    Import-Module Microsoft.Graph.Groups
    
    Remove-MgGroupMemberByRef -GroupId $groupId -DirectoryObjectId $directoryObjectId
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.