[Powershell] Export CSV structure form get-adprincipalgroupmembership

Stoycho Kushev 1 Reputation point
2021-01-27T16:18:51.577+00:00

Hello All,

I'm trying to generate report in CSV format for my AD users.
However I want to make it in the following structure - collumn headers be: Name, Username, Group0, Group1, Group3 and so on based on the highest number of groups a user has. (Example attached as screenshot)
61082-picture.png

In other words a dynamically expanding custom object.
I've written this:

Get-Aduser -Filter * -SearchBase "OU=Admins,DC=vlab,DC=test" -Properties Name, SamAccountName, LastLogonDate, whencreated | select Name, SamAccountName, LastLogonDate, whencreated | export-csv C:\TS_Users.csv -NoTypeInformation  
  
  
$Users = Import-Csv -Path C:\TS_Users.csv   
$Result = foreach ($User in $Users){  
         $Object = [pscustomobject]@{   Name = $User.Name  
                                        Username = $User.SamAccountName  
                                    }  
         $Groups = Get-ADPrincipalGroupMembership -Identity $User.SamAccountName | Select-Object -Property name  
           
                   $i = 0  
                   foreach ($Group in $Groups){  
                     
                   $PropertyName = "Group$($i)"  
                 
                   Add-Member -InputObject $Object -NotePropertyName $PropertyName -NotePropertyValue $Group.name  
                   $i++                          }  
          $Object  
                                       }  
$Result | Export-Csv C:\Users_Groups.csv -NoTypeInformation  

However I am getting as much results as the number of groups my first user has.
Is there a way to do this properly ?

Best Regards,
Kushagi

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,462 questions
{count} votes