-1

I have a list of AD security groups contained in a .csv file, in the following format:

Groups,
Groupname1,
Groupname2,
Groupname3,

What I want to do is feed this .csv file to a PowerShell script, so it can report on the group membership of the groups listed in the .csv file (I don't care about recursive groups, as I don't have any). The script should then dump the results to a further .csv file.

So, ideally, I want the final .csv produced output from the scripts to be something like.

Groupname1, name
Groupname1, name
Groupname2, name
Groupname2, name
Groupname3, name
Groupname3, name

You get the idea.

What I am struggling with is getting some sort of for loop going, to look through all the groups from the .csv and output the results as shown above (groupname and then user).

$list = Import-Csv -Path C:\temp\ADGroups.csv

foreach ($groups in $list) {
  $ADGroup = $groups.groupname

  Get-ADGroupmember -Identity $ADGroup | Get-ADUser -Property Name
  Export-Csv -Path "c:\temp\dump.csv"
} 

I've seen other suggestions (see example here), but these don't read the groups from a .csv file.

Community
  • 1
  • 1
SimonM73
  • 13
  • 2

1 Answers1

2

You need to add the group name to the output. I would do this with a calculated property. You also need to move the Export-Csv outside the loop or use -Append. If not, the groups will overwrite the file every time and it will only contain the results from the last group. Try this:

Import-Csv -Path C:\temp\ADGroups.csv | Foreach-Object { 

    $ADGroup = $_.Groups

    Get-ADGroupmember -identity $ADGroup | Select-Objects @{n="Groupname";e={$ADGroup}}, Name
} | Export-CSV -Path  "c:\temp\dump.csv" -NoTypeInformation
Frode F.
  • 52,376
  • 9
  • 98
  • 114