CSV export with Groups in a Group

Hello
I am trying to create an export with all members from a group.
But I wan’t not only the members i want also the groups in this specific group in a list.

My script only shows the users but i don’t find the nested groups in this specific group.

Get-ADGroupMember -identity “my-group” -recursive | select name,samaccountname | Export-csv -path C:\temp\Members_and_groups.csv -NoTypeInformation

Can someone please help me.
It would be nice to have posibility to export both in one script Users and the groups in a specific group. I have a mix in the AD, I finde groups which only have users and i find groups which have other groups (nested).

Thanks for your help

stef74,
Welcome to the forum. :wave:t4:

When you use the parameter -Recursive PowerShell drills down into all nested groups. You should omit this parameter and check the object class of the members of the group to distinguish the users from the groups.

BTW: Could you please format your code as code using the preformatted text button ( </> ). Simply place your cursor on an empty line, click the button and paste your code.
Thanks in advance.

Hello Olaf
Next Time I will do it right with the code.
I am still not able to modifie the code to get users and groups in the same export, which are in the “register” members.
Guess I need an example.
Greetings

Here’s how to see what is a user and what is a nested group:

$Group = 'my-group'
$GroupMemberList = 
    Get-ADGroupMember -Identity $Group | 
        Sort-Object -Property ObjectClass -Descending
$Results =
foreach ($GroupMember in $GroupMemberList) {
    [PSCustomObject]@{
        Group          = $Group
        sAMAccountName = $GroupMember.sAMAccountName
        Name           = $GroupMember.Name
        ObjectClass    = $GroupMember.ObjectClass
    }
}
$Results | Export-Csv -Path .\Results.csv -NoTypeInformation

Depending on the amount of groups and the depth of nested groups in your AD and on your enthusiasm you could turn it into a recursive function or you “drill down” into the nested groups manually and piece it together with an Export-Csv -Append. :wink:

Thank you for the help, it works fine

But I don’t know where or how to put the export -csv, becaus I wish to export the results

… did you try to search for it? :wink:

I updated my code suggestion above. You collect the output of the foreach loop in a variable and pipe this variable to Export-Csv.

Hi Olaf, thanks for your help, my problem is, that I am not very used to powershell. I tryied but I failed

We all have been at that point. And we all do not know everything. :wink: In the vast majority of the cases you’re not the first with a given challenge. Use your favorite internet search engine and search for it. It’ll probably take you just seconds to find some helpful information. :wink:

1 Like