Multiple member lists from AD into the same csv file?

Welcome Forums General PowerShell Q&A Multiple member lists from AD into the same csv file?

This topic contains 1 reply, has 2 voices, and was last updated by

 
Participant
1 month, 1 week ago.

  • Author
    Posts
  • #170020

    Participant
    Topics: 1
    Replies: 0
    Points: -9
    Rank: Member

    Hi there!

    Complete newbie here – trying to figure out how to accomplish the following:

    • Use an existing .csv list of all the user groups in AD I want to pull (in one column)
    • Use grab each user group from the column
    • Find that user group in AD
    • Pull the member names
    • Put those member names into its own column in a new .csv
    • Rinse and repeat until all of those user groups have been found
    • Export the .csv

    For reference the code I'd been using before was the following:

    $Groups = Get-Content -Path 'c:\Users\arielle.admin\Desktop\USERGROUPS.csv'
    foreach ($Group in $Groups)
    {
    Get-ADGroupMember -Identity $Group | Export-Csv -Path "c:\Users\arielle.admin\Desktop\$group.csv"
    }

    This was able to export each group into its own .csv, which was helpful, except it'd be so nice to be able to open up a single document and see all of my member names in its own column, and I couldn't specify that I only needed the "name" column.

    Any advice would be greatly appreciated!! Thank you so much in advance.

  • #170032

    Participant
    Topics: 1
    Replies: 1529
    Points: 2,587
    Helping Hand
    Rank: Community Hero

    Assuming your input CSV file has a header "Name" for the name of your groups you could use something like this:

    $GroupList = Get-Content -Path 'c:\Users\arielle.admin\Desktop\USERGROUPS.csv'
    $Result = foreach ($Group in $GroupList) {
        $GroupMemberList = Get-ADGroupMember -Identity $Group.Name
        [PSCustomObject]@{
            GroupName         = $Group.Name
            MemberSamAccounts = $GroupMemberList.sAMAccountName -join ','
            MemberName        = $GroupMemberList.Name -join ','
        }
    }
    $Result | 
        Export-Csv -Path "c:\Users\arielle.admin\Desktop\GroupsWithMembers.csv" -NoTypeInformation

You must be logged in to reply to this topic.