How to Remove a User from Office 365 Group using PowerShell?

Requirement: Remove user from office 365 group using PowerShell

How to Remove a User from Office 365 Group?
As an admin, you can remove members from any Office 365 group through Microsoft 365 admin center. Here is how:
  • Login to the Microsoft 365 Admin Center site: https://admin.microsoft.com
  • Expand Groups and Click on Groups link in the left navigation. 
  • Search and Select the Office 365 group you wish to remove members.
  • In the Group details page, Click on "Members" tab >> Click on View all and manage members link. 
    remove user from office 365 group
  • Now you can remove group members by clicking on the "X" button next to each member. Hit save once you are done!
    remove user from office 365 group powershell

PowerShell to Remove User from Office 365 Group 
Here is how we can use PowerShell to remove a user a office 365 group:
#Variables
$GroupName = "IT Team"
$UserUPN = "salaudeen@crescent.com"

#Connect to AzureAD
Connect-AzureAD -Credential (Get-Credential)
 
#Get the Azure AD Group
$AADGroup = Get-AzureADGroup -Filter "DisplayName eq '$GroupName'"

#Get the Azure AD User
$AADUser  = Get-AzureADUser -Filter "UserPrincipalName eq '$UserUPN'"

#Remove User from Group
Remove-AzureADGroupMember -ObjectId $AADGroup.ObjectID  -MemberId $AADUser.ObjectID 

Similarly, You can remove a user from all Office 365 Groups quickly through PowerShell
#Variables
$UserUPN = "salaudeen@crescent.com"

#Connect to AzureAD
Connect-AzureAD -Credential (Get-Credential) | Out-Null
 
#Get all Azure AD Unified Groups
$AADGroups = Get-AzureADMSGroup -Filter "groupTypes/any(c:c eq 'Unified')" -All:$true

#Get the Azure AD User
$AADUser  = Get-AzureADUser -Filter "UserPrincipalName eq '$UserUPN'"

#Check each group for the user
ForEach ($Group in $AADGroups) 
{
    $GroupMembers = (Get-AzureADGroupMember -ObjectId $Group.id).UserPrincipalName
    If ($GroupMembers -contains $UserUPN)
    {
        #Remove user from Group
        Remove-AzureADGroupMember -ObjectId $Group.Id -MemberId $AADUser.ObjectId 
        Write-Output "$UserUPN was removed from $($Group.DisplayName)"
    }
}
How to Remove a User from Office 365 Group using PowerShell? How to Remove a User from Office 365 Group using PowerShell? Reviewed by Salaudeen Rajack on January 07, 2019 Rating: 5

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.