Powershell – Getting Group Membership in Office365

As I’m trying to clean up some accounts, I found that it’s -not easy- to simply get a list of all the groups a user is a member of in powershell, at least not like the one that displays in the admin portal. In doing some hunting (admittedly, not a lot of hunting) I came across this site that has just about what I was looking for, but I will warn you that the one-liners provided are not efficient – they have to populate the members of all groups, therefore if you have a LARGE directory, these may take a very long time to run, and be data-intensive. If you’re an SMB or SME with only a couple hundred users, they should be OK.

https://absolute-sharepoint.com/2018/03/find-all-the-office-365-groups-a-user-is-a-member-of-with-powershell.html?unapproved=397014&moderation-hash=b59b197881609389d441464bd17d72bb#comment-397014

The problem was, it didn’t work! It looked good, but the variable it stored the results in was empty. After a quick review I realized the problem; the $mailbox.Alias at the end of the scripts should have been $mailbox.Name, since the alias will never match the name shown in the group membership. Once I changed that, it worked as it should:

$Office365GroupsMember = Get-UnifiedGroup | where { (Get-UnifiedGroupLinks $_.Alias -LinkType Members | foreach {$_.name}) -contains $mailbox.Name}

However…this only works for “Office365” Groups, and not all Office365 group types, that may include groups sync’ed from Active Directory/DirSync, like distribution lists and so on. I took the one-liner from that site, and modified it slightly to use “get-msolgroup” rather than get-unifiedgroup, which worked as it should.

$UserEmail= "someperson@somecompany.com"
 
$Mailbox = Get-Mailbox | Where {$_.PrimarySmtpAddress -eq $UserEmail}

Get-msolGroup | where { (Get-msolGroupmember -GroupObjectId $_.objectid | foreach {$_.displayname}) -contains $mailbox.name}

From there you can pipe the output of that command into others, like remove-msolgroupmembership (although it needs the member objectid which is odd), or store it in a variable. Keep in mind you may want to filter group types as well, as I’m not sure you can remove a user from an Office365 group that was added/created as part of a Teams teams.

Last but not least, see these commands to do simliar roles for Active Directory:
get-adprincipalgroupmembership
remove-adprincipalgroupmembership

I figured this might help someone out, and kudos to the other page for having a one-liner that worked as the basis for this!