1
votes

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?

2
There is a curly bracket missing, but it's before the last pipe. Should be: ... | select -exp name}} | where {$_.groups}Ansgar Wiechers

2 Answers

1
votes

First of all I'am afraid that Get-ADuser -Filter {group -eq 'Domain Users'} just give nothing.

You can try to begin :

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

Then you can modify the filter to also take InetOrgPerson.

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

Then you can take the samAccountName of the group DN

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

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