Search code examples
powershellactive-directoryldapwindows-server-2012-r2

Output list of all Active Directory users and all groups each user is a member of


I'm trying to query Active Directory to get a list of all users and all groups each user is a member of. I only need the direct groups each user is a member of, not the nested groups. The end-goal is to output this list to a CSV file. I'm attempting to do this using PowerShell in Windows Server 2012 R2.

UPDATE

So I've now managed to output a list of all users' names, however only some of the users's groups are included in the output, using the following command:

Get-ADuser -LDAPFilter "(objectClass=user)" -property "memberOf" | 
select -Property @{n='name';e={$_.name}},@{n='groups';e
{$($_.MemberOf | Get-adgroup | % {$_.name}) -join ','}}

I'm unable to determine why only some of the users output (probably only 5-10 total) include the groups the user is a member of, while the rest (95%) of the users output only display the name of the user, without any groups at all.

Any ideas from here?


Solution

  • Late reply to this post, but I built a script that output all Groups in a specific OU and all users of each group. Only downside is that the "owner" of each group is also a member, so there is a bit of redundancy, but nothing breaking for my purpose. The output is formatted into two columns.

    $mGroups=@(
    Get-ADGroup -filter * -SearchBase "OU=,OU=,OU=,DC=,DC=" | select name);
    
    
    $col = @()
    for ($i=0
     $i -lt $mGroups.Count;
     $i++)
     {
          $agents=@(
          Get-ADGroupMember $mGroups[$i].name | select sAMAccountName)
    
            for ($n=0
                 $n -lt $agents.Count;
                 $n++)
                 {
                  $agentList = [PSCustomObject]@{
                  Group = $mGroups[$i].name 
                  Agents = $agents[$n].sAMAccountName
                 }
                $col+=$agentList;
                 }
       }          
    $col
    $col | Export-CSV -NoTypeInformation C:\Path\to\file.type