You could try this. Be sure to remove (or just comment out) one of the ways to create the CSV (one row per user/group, OR one row per user with all groups):
Get-ADUser -Filter * -SearchBase "OU" -Properties memberOf |
Foreach-Object{
# $_ represents a user object
$var = [PSCustomObject]@{
SID = $_.SamAccountName
Name = $_.Name
Group = ""
}
# create one row for each user/group combination
$_.memberOf |
ForEach-Object{
# $_ represents a group's distinguishedName
$var.Group = (Get-ADGroup $_).samaccountname
$var
}
# ---- OR ------
# create one row for each user, all groups in "Group" column, each separated by ';'
if ($_.memberOf){
$groups = @()
$_.memberOf |
ForEach-Object{
$groups += (Get-ADGroup $_).samaccountname
}
$var.Group = $groups -join ';'
$var
}
} | Export-Csv -Path C:\Temp\GrpMembers.csv -NoTypeInformation