Powershell list all active domain users with group membership

powershell

How can I get a list of all active domain users with group membership and one user per line?

I have tried:

Import-Module Activedirectory
Get-ADUser -Filter 'enabled -eq $true' -Properties SamAccountname,DisplayName,memberof | % {
New-Object PSObject -Property @{
UserName = $_.DisplayName
Groups = ($_.memberof | Get-ADGroup | Select -ExpandProperty Name) -join 
","}
} | Select SamAccountname,UserName,Groups 

but SamAccountname is empty.

Best Answer

You don't have SamAccountname because powershell searchs this property in your custom object which you create with New-Object. If you want to retrieve SamAccountname in this object you must modify to have :

Get-ADUser -Filter 'enabled -eq $true' -Properties SamAccountname,DisplayName,memberof | % {
New-Object PSObject -Property @{
UserName = $_.DisplayName
oSamAccountname= $_.SamAccountname
Groups = ($_.memberof | Get-ADGroup | Select -ExpandProperty Name) -join 
","}
} | Select oSamAccountname,UserName,Groups