Active Directory – How to Generate a Group Membership Report

Another small one today, the script below will generate a nice csv export of every single group and it’s active user membership from Active Directory. The next step would likely be to turn it into a nice Pivot Table for reviewing.

It should be fairly straightforward to change it to show all users or all users & computers etc as required.

Requirements

The Script

Replace the $ExportLocation variable with the location you want to export the result to.

$ExportLocation = "********\ADAxport.csv"

# Get a list of all Active Directory groups
$ADGroupNames = Get-ADGroup -filter * | sort Name | select Name, SamAccountName
$ExportData = @()

# Set the current index to 1 (Used for a progress bar)
$currentIndex = 1

# Loop through all groups
foreach($GroupName in $ADGroupNames) {
    # Show a nice progress bar
    Write-Progress -Id 0 -Activity "Building report from Active Directory" -Status "$currentIndex of $($ADGroupNames.Count)" -PercentComplete (($currentIndex / $ADGroupNames.Count) * 100)

    # Get all membership of a given group and select only the users
    $GroupMembership = Get-ADGroupMember -Identity $GroupName.SamAccountName -Recursive | Where {$_.objectClass -eq "user"} | select distinguishedName
    # Retrieve all of the active users from the list, selecting only the name
    $GroupMembershipUsers = $GroupMembership | ForEach-Object {Get-ADUser -Identity $_.distinguishedName -Properties Enabled} | select Name

    # For each member add a new object to the ExportData array
    foreach($User in $GroupMembershipUsers) {
        $ExportData += [PSCustomObject]@{
            Group = $GroupName.Name
            User = $User.Name
        }
    }

    # Increment the index
    $currentIndex++;
}

# Reset the progress bar
Write-Progress -Id 0 -Activity " " -Status " " -Completed

$ExportData | Export-Csv -Path $ExportLocation -NoTypeInformation

One thought on “Active Directory – How to Generate a Group Membership Report

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.