Export groups and username of a user in Active Directory

1.1k views Asked by At

I am trying to find out the Active Directory groups all our active users are in and want to export it to a CSV file. However the following command presents garbage in the related CSV file.

This is my code failing:

Import-Module ActiveDirectory
Get-ADUser -SearchBase "CN=Users,DC=Mycompany,DC=de" -Filter * |  where { $_.enabled -eq "true" } | foreach-object {
    write-host "User:" $_.Name 
    Get-ADPrincipalGroupMembership $_.SamAccountName | foreach-object {
        write-host "Member of:" $_.name | export-csv "C:\scripts\output\ad-user-with-group-memberhip.csv" -NoTypeInformation -Encoding UTF8
    }
}

Any idea what am I doing wrong here?

1

There are 1 answers

0
Theo On BEST ANSWER

Write-Host only writes text to the console window. It doesn't output anything useful to pipe through to Export-Csv.
Also, unless you add switch -Append, you should set the Export-Csv cmdlet as last line in the code, otherwise you will overwrite it in every iteration.

Try

with Select-Object

Import-Module ActiveDirectory
Get-ADUser -SearchBase "CN=Users,DC=Mycompany,DC=de" -Filter "Enabled -eq $true" | 
Select-Object Name, @{Name = 'Groups'; Expression = {($_ | Get-ADPrincipalGroupMembership).Name -join '; '}} |
Export-Csv -Path "C:\scripts\output\ad-user-with-group-memberhip.csv" -NoTypeInformation -Encoding UTF8

or with ForEach-Object

Import-Module ActiveDirectory
$result = Get-ADUser -SearchBase "CN=Users,DC=Mycompany,DC=de" -Filter "Enabled -eq $true" | 
ForEach-Object {
    [PsCustomObject]@{
        Name = $_.Name
        Groups = ($_ | Get-ADPrincipalGroupMembership).Name -join '; '
    }
}
$result | Export-Csv -Path "C:\scripts\output\ad-user-with-group-memberhip.csv" -NoTypeInformation -Encoding UTF8