Memberof property not outputting all groups a user is a member of

I'm having an issue running this script. it works the way it's supposed to, aside from the fact that its not outputting all groups a member is a part of. none of the groups are nested.

$Ous = “ou=ou1,ou=ou2,dc=ou3,dc=com”

Function GetAllGroups {
foreach($Ou in $Ous){
Get-ADUser -filter * -searchbase $Ou -properties memberof |
Group-Object -property memberof |
foreach-object {
foreach($Item in $.Group){
Name = $Item.Name
GroupName = ($
.Name -split ‘,’) -join ‘,’ -replace “OU=Groups,OU=[company]OU=[division],OU=[domain],DC=[domain],DC=com”


GetAllGroups |export-csv c:\scripts\userallgroups567.csv -notypeinformation -append

Any ideas why some groups would be missing? sometimes it's domain users, sometimes its another group, primarily the same group, unless a user has no other group memberships, than that group is displayed.. its real odd.
I'm not sure how to format as code, sorry

First of all - could you please format your code as code? In the Visual view you can use the format template Preformatted. You can go back edit your post and fix the formatting - you don’t have to create a new one.
Thanks in advance.

You try to group the output of Get-ADUser by the property MemberOf. MemberOf is - probably most of the time - an array. It does not make any sense to use Group-Object in this case. Besause you will not get reliable and reproducable results.

What is it what you’re actually trying to do?

So what I would like to do is output a list of every user in our company ou, and every group that user belongs to.

To reduce the stress you put on your AD I’d recommend to query the AD only twice. Once for the groups and once for users. After that you work with the local variables.

$OUList    = "ou=ou1,ou=ou2,dc=ou3,dc=com","ou=ou4,ou=ou5,dc=ou6,dc=com"
$GroupList = Get-ADGroup -Filter *
$UserList  = 
  foreach ($OU in $OUList) {
    Get-ADUser -Filter * -SearchBase $OU -Properties MemberOf

$output =
  foreach ($User in $UserList) {
  $MemberOfList = 
    foreach ($Group in $User.MemberOf) {
      $GroupList | Where-Object -Property DistinguishedName -EQ -Value $Group
      User   = $User.Name
      Groups = $MemberOfList.Name -join ', '
$output |
  Export-Csv -Path 'c:\scripts\userallgroups567.csv' -NoTypeInformation


I wonder if this may be some kind of bug. Your code works great, but its still not outputting certain groups for random users. We have a local admins group that pretty much every user has, and that’s the group that seems to be missing the most when I run the script, even though its there if I look in aduc.

You may check if this group is set as primary group for some of your users. It will not be listed in the MemberOf attribute.