i am trying to export all the users and their membership in an excel file

I looking for the following format

Name GroupsMembership

User1 Group1

User2 group1, group2

get-aduser user -Server domainname |select name, @{Name=“GroupsMembership”;Expression={(Get-ADPrincipalGroupMembership $_.DistinguishedName.ToString() -server domainname)}}

I tried this but GroupsMembership is showing in a different format . can I exactly get the group name?

its showing like {CN=Domain Users,OU=Security,OU=Group

the reason why I mention server name is we have multiple domains.

7 Spice ups

Hello yoee, try this.

Get-ADUser -Identity user -Properties name | select name, @{Name="GroupsMembership";Expression={[string]::Join(';',(Get-ADPrincipalGroupMembership -Identity $_ | select -ExpandProperty name))}}

If you do not want to join the groups by semi-colon, just replace that with whatever you want to join by.

@

Jasoncramsey Thanks very much , we have multiple domain. do we need to run the same for each domain? and how to get all the users of a specific domain?

@jasoncramsey

Yes, you could run it once for each domain, or create an array of domains then use a foreach loop to process all domains.

$Domains = @('domain.com','domain.local','company.net')
foreach ($Domain in $Domains) {Get-ADUser -Server $Domain ...}

But the account you are running PS as would need to have access to all the domains.

1 Spice up

@jasoncramsey

$Domains = @(‘domain.com’,‘domain.local’,‘company.net’)
foreach ($Domain in $Domains) {Get-ADUser -Server $Domain -Properties name,mail,enabled | select Name,Mail, Enabled, @{Name=“GroupsMembership”;Expression={[string]::Join(‘;’,(Get-ADPrincipalGroupMembership -Identity $_ | select -ExpandProperty name))}} | Export-Csv “C:\test.csv”

I tried this script and got the error below and the output only has a few details.

Get-ADUser : The server has returned the following error: invalid enumeration context.
At line:3 char:2