[Powershell] Export CSV structure form get-adprincipalgroupmembership
Stoycho Kushev
1
Reputation point
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)
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