Windows – How to list all Active Directory Users and their group membership

active-directorypowershellwindows

I'd like a single scripted line to export to CSV all the users in my AD with all the groups they are members of.

I'd prefer it to be done in powershell, but dsquery/dsget is a fine alternative really.

EDIT: i have trying to do something like this:

$user="administrator"
(GET-ADUSER -Identity $user -Properties MemberOf | Select-Object MemberOf).MemberOf

But i'd like to have a loop of the $user variable to be changed by each line in reference text file.

This is the point were I don't know how to loop it.

Best Answer

Install the Quest CMDlets and then run this code:

Add-PSSnapin Quest.ActiveRoles.ADManagement
$memberships = @()

Get-QADGroup -SizeLimit 0 | Foreach-Object {
        $NameGroup = $_.Name
        Write-Host "Working with $NameGroup"
        $membership = Get-QADGroupMember $_.DN -Enabled -SizeLimit 0
        if ($membership -ne $null ) {
        $membership | Add-Member -type NoteProperty -name AuditGroupUserIsMemberOf -value $_.Name
        $memberships += $membership
        }
    }

$memberships | Select-Object AuditGroupUserIsMemberOf, NTAccountname | Export-Csv "GroupsWithUsers.csv"

This will give you a 1 record per group-user connection so expect multiple occurrences of users and groups. If you wan't other fields, you can just edit the Select-Object statement. Use $memberships | gm to see all the possibilities for the users. If you want more fields for the groups, use Get-QADGroup | gm, you will then need to add these by adding a new NoteProperty.

If you don't really care about more options, here is a one-liner you can just mash in the terminal:

Get-QADGroup -sizeLimit 0 | select @{name="Group";expression={$_.name}} -expand members | select Group,@{n='User';e={ (Get-QADObject $_).NTAccountName}} | Export-Csv "MyUsersAndGroups.csv"