Search code examples
powershellactive-directoryexport-to-excel

ADGroups AND ADusers


I need to get the following into a CSV:

Groups with fields: group name, group SID, group email address, group type

and then for each of the above groups i need the member users with the fields: group name (I know that's a repeat), userID, user firstname, userlastname, user email.

If someone has a solution for this I will be forever grateful. The solution will be something I can study and learn from so thanks again.

I have the two pieces separately but am stuck at that point

Get-ADGroup -Filter * -Properties Member |
    select Name, DistinguishedName, sid, GroupCategory, GroupScope,
        @{Name="Members";Expression={($_.Members | Measure-Object).Count}} |
    Out-GridView
    #Export-Csv c:\rmm-mgmt\test.csv

I don't understand why the user details can't just be added as well. For the users I'm using:

Get-ADUser -Filter * -Properties * |
    Select-Object name, surname, givenname, displayname, emailaddress |
    Out-GridView

(Using Out-GridView to check results before I begin exporting)

As you can see these are two pieced of information I can get but can't put them together. One example is I can't get the list of members in groups.


Solution

  • You have to use ForEach-Object and assign the group to a named variable so you can access it where you format each member. Then pipe $_.Member into Get-ADUser:

    Get-ADGroup -Filter * -Properties Member | ForEach-Object {
        $group = $_
        $_.Member | Get-ADUser -Properties Surname,GivenName,DisplayName,EmailAddress |
            Select @{N = "Group Name";E = {$group.Name}}, Surname, GivenName, DisplayName, EmailAddress
    } | Out-GridView