Export Group Membership of a User in AD and Entra

Hi All,
Recently i wanted to export the Groups of a User. Here is some code i used for Active Directory and Entra ID.
Active Directory
First let’s look into Active Directory. We can use the Get-ADUser commandlet and specify the “MemberOf” Property
###############################################################################
# AD GroupMember
###############################################################################
$SamAccountName = "m.muster"
$DomainController = (Get-ADDomainController).HostName
$User = Get-ADUser -Identity $SamAccountName -Properties "Memberof" -Server $DomainController
$Groups = $User.MemberOf
$Groups
After sime String Magic we have the GroupName
$GroupsArray = @()
Foreach ($Group in $Groups)
{
$GroupName = $Group.Split(",")[0].Replace("CN=","")
#Write-Host "$GroupName"
$GroupsArray += $GroupName
}
$GroupsArray = $GroupsArray | Sort-Object
Entra ID
Let’s do the same with Entra ID
###############################################################################
# Entra GroupMember
###############################################################################
Connect-MgGraph -Scope user.read.all -NoWelcome
$EntraGroupMembers = Get-MgUserMemberOf -UserId "m.muster@icewolf.ch"
$EntraGroupMembers
We get the Group ID’s and could get the Group Details with Get-MgGroup
# Get Groupdetails with GroupID
Get-MgGroup -GroupId $EntraGroupMembers[0].id
Get-MgGroup -GroupId $EntraGroupMembers[0].id | fl
But we have most of the needed Group details already in the AdditionalProperties
# Everything already in Additional Properties
$EntraGroupMembers[0].AdditionalProperties
Let’s loop through the groups and create a PSCustom Object with the Attributes we want
$ArrayGroups = @()
Foreach ($EntraGroup in $EntraGroupMembers)
{
If ($Null -ne $EntraGroup.AdditionalProperties.groupTypes)
{
$GroupType = $EntraGroup.AdditionalProperties.groupTypes[0]
} else {
$GroupType = $EntraGroup.AdditionalProperties.groupType
}
$myObject = [PSCustomObject]@{
Id = $EntraGroup.Id
displayName = $EntraGroup.AdditionalProperties.displayName
securityEnabled = $EntraGroup.AdditionalProperties.securityEnabled
mailEnabled = $EntraGroup.AdditionalProperties.mailEnabled
groupType = $GroupType
}
$ArrayGroups += $myObject
}
#Output
$ArrayGroups | Sort-Object displayName | ft
Or show a Gridview of the Result. That can be easy copied to Excel for further processing.
# Output to GridView
$ArrayGroups | Sort-Object displayName | Out-GridView
Summary
I’ve showed you how you can get the Groups of a User.
It’s easy to export that into a CSV or use “Out-Gridview”.
Happy PowerShell coding 😎
Regards
Andres Bohren