Help with Powershell Script


I am new to powershell and I have to create a script to do the following :

I need to get a list of AD groups and extract the users in a CSV file. I can do that fine but I don’t know how to divide the users by AD groups in the CSV file.

I have the below script but all the users are listed together :

foreach ($line in import-csv \\Path\ListofADgroups.csv){Get-ADGroupMember -Identity $line.Name -Recursive | Get-ADUser -Property DisplayName | Select Name,ObjectClass,DisplayName | Export-Csv -Path C:\temp\Users.csv | -NoTypeInformation -append}

In the ListofADgroups.csv file there is a long list of AD groups. I am trying to list the users by AD group in the CSV file.


Any help would appreciated.

Thank you so much

A noob


Enrica, welcome to Please take a moment and read the very first post on top of the list of this forum: Read Me Before Posting! You’ll be Glad You Did!.

When you post code or error messages or sample data or console output format it as code, please.
In the “Text” view you can use the code tags “PRE“, in the “Visual” view you can use the format template “Preformatted“. You can go back edit your post and fix the formatting – you don’t have to create a new one.
Thanks in advance.

If I understood you correctly, I think this will do it.

foreach ($line in import-csv \\Path\ListofADgroups.csv){
    Get-ADGroupMember -Identity $line.Name -Recursive | foreach {
        get-aduser $_ -Property displayname | Select Name,ObjectClass,DisplayName |
            Select @{N='ADGroup';e={$line.Name}},
    } | Export-Csv -Path C:\temp\Users.csv -NoTypeInformation -append

Thank you very much, that is exactly what I needed. I have also fixed the formatting of my post :slight_smile:


Win and win! I’m glad to help. Take care.