powershellactive-directorydistribution-list

get list of DLs few users are member of


I am beginner in powershell and trying to create a script. I have list of users, for them I need to know in which DLs they are added.

The problem I am facing is, it shows the list of DLs only, is there any way I can get DLs under the usernames? or a better way to accomplish this.

Note: we name all our DLs in capital letter thats why I have used "\b[A-Z0-9_]+\b" in where-object.

$users = import-csv C:\Test\users.csv | ForEach-Object {$_.users = $_.users.Trim(); $_}  | Select-Object -ExpandProperty users

foreach ( $user in $users)

{get-ADPrincipalGroupMembership $user | select name |

Where-Object { $_.name -cmatch "\b[A-Z0-9_]+\b"} | Export-CSV "C:\test\output_file.csv" -NoTypeInformation -Append

}

Now I get the following outcome:

Group1
Group2
Group3
Group2
Group3
Group4

My ideal out put would be something along the lines of:

User  MemberOf
----  --------
Bob   Group1, Group2, Group3....
Jim   Group2, Group3, Group4....

Thanks alot.


Solution

  • Assuming you're looking for Distribution Lists, you can tell if a group is a Security Group or a Distribution List by looking at the GroupCategory property of an ADGroup object.

    Instead of looking at the user's memberOf attribute and finding out which ones are Distribution you can search for ADGroups that are GroupCategory -eq 'Distribution' where each user is a member:

    $users = (Import-CSV C:\Test\users.csv | ForEach-Object {
        $_.users.Trim()
    }).users
    
    $result = foreach ($user in $users)
    {
        $userDN = (Get-ADUser $user).DistinguishedName
        $groups = Get-ADGroup -Filter "member -eq '$userDN' -and groupCategory -eq 'Distribution'"
        
        [pscustomobject]@{
            User = $user
            MemberOf = $groups.Name -join ', '
        }
    }
    
    $result | Export-CSV "C:\test\output_file.csv" -NoTypeInformation
    

    If you want to use the code you already have, with this minor update you should be getting the result you are looking for:

    $users = (Import-CSV C:\Test\users.csv | ForEach-Object {
        $_.users.Trim()
    }).users
    
    $result = foreach ($user in $users)
    {
        $membership = Get-ADPrincipalGroupMembership $user |
        Where-Object {
            $_.name -cmatch "\b[A-Z0-9_]+\b"
        }
    
        [pscustomobject]@{
            User = $user
            MemberOf = $membership.Name -join ', '
        }
    }
    
    $result | Export-CSV "C:\test\output_file.csv" -NoTypeInformation