Search code examples
powershellactive-directoryactive-directory-group

Export AD users with list of specific groups


I've been trying to get an extract of AD users and select mail, name, memberof. I then need to list only specific groups from the memberof output so I end up with a list for each user than contains their name, email address and specific groups that match a certain name and not all of the groups they are a member of.

Get-ADUser username -Properties memberof | Select-Object memberof

I can't seem to find a way of doing this as I end up with either noteproperty above or an empty pipeline. Is there a way to achieve what I am trying to do?


Solution

  • The memberOf attribute contains a list of distinguishedName (DN) values, each corresponding to a group.

    Retrieve the groups you are interested in, before you run Get-ADUser, that way you can compare the Group DN to the entry in memberOf:

    $GroupDNs = Get-ADGroup -Filter {Name -like "*finance*" -or Name -like "*creditcontrol*"} | Select-Object -ExpandProperty DistinguishedName
    

    Now, you can use those DN's to filter the group memberships with a calculated property, like so:

    $UserInfo = foreach($username in @("bob","alice","joe")){
        $User = Get-ADUser -Identity $username -Properties mail,memberOf |Select Name,mail,memberof
        $User | Select-Object Name,mail,@{Label="GroupDNs";Expr = {$_.memberof | Where-Object {$Groups -contains $_}}}
    }
    

    without doing a new Get-ADGroup query for each memberof entry.

    If you want a string of group names, rather than a NoteProperty containing an array of strings, you could fill the Groups into a hashtable and use that to "look up" the memberof entries using the ContainsKey() method:

    $Groups = @{}
    Get-ADGroup -Filter {Name -like "*finance*" -or Name -like "*creditcontrol*"} | ForEach-Object {
        $Groups[$_.DistinguishedName] = $_
    }
    
    $UserInfo = foreach($username in @("bob","alice","joe")){
        $User = Get-ADUser -Identity $username -Properties mail,memberOf |Select Name,mail,memberof
        $User | Select-Object Name,mail,@{Label="Groups";Expr = { ($_.memberof | Where-Object {$Groups.ContainsKey($_)} | ForEach-Object { $Groups[$_].Name}) -join ";" }}
    }
    
    $UserInfo | Export-Csv C:\aduserinfo.csv -NoTypeInformation