Export AD groups name as heading and its members to their respective rows in csv

Hi Team,

I am working on file server migration project. I am trying to export data in csv file for AD groups and their members. I want to export data in csv below format:

ADGroup1                    ADGroup2
Jason Ross                  Joe Butler      
Anthony Davis               Jerry Anderson

I am using below script. It is working for one AD group if I have in txt file. If I add multiple groups in my text file, it overrides to the previous one. I need guidance to export the data for multiple AD groups.

 $groups = Get-Content C:\temp\ADGroups.txt
 $groupname = @()
 $groupmember = @()

foreach ($g in $groups){

$groupname += Get-ADGroup -Identity $g | Select-Object -ExpandProperty Name
$groupmember += Get-ADGroupMember -Identity $g | 
Select-Object -ExpandProperty SamAccountName

for ($i = 0; $i -le $groupmember.Count; $i++) {
      [PSCustomObject]@{

    $g = $groupmember[$i]

      } | Export-Csv -Path C:\temp\result.csv -Append -NoTypeInformation
}                  
}

Any help would be appreciated.

Thanks
Jatinder

The format you desire as output might feel like a great idea but it’s actually not. It would be even hard to read it again with PowerShell for further steps later on. :wink:

You have basically 2 options.
#1

$groupList = Get-Content C:\temp\ADGroups.txt
$Result = 
foreach ($group in $groupList) {
    $GroupMemberList = Get-ADGroupMember -Identity $Group 
    [PSCustomObject]@{
        GroupName       = $group
        GroupMemberList = $($GroupMemberList.sAMAccountName) -join ','
    }
}
$Result | Export-Csv -Path C:\temp\result_01.csv -Delimiter ',' -NoTypeInformation

This way you have one group per line and the groupmembers in one big chunk in the second column delimited by a comma.

#2

$groupList = Get-Content C:\temp\ADGroups.txt
$Result = 
foreach ($group in $groupList) {
    $GroupMemberList = Get-ADGroupMember -Identity $Group 
    foreach ($GroupMember in $GroupMemberList) {
        [PSCustomObject]@{
            GroupName   = $group
            GroupMember = $($GroupMember.sAMAccountName)
        }
    }
}
$Result | Export-Csv -Path C:\temp\result_02.csv -Delimiter ',' -NoTypeInformation

This way you have one groupmember per line with its group in the first column.

2 Likes