List Users and their Group Membership using PowerShell

In some cases you might need to prepare a report on list of Active Directory users and their group Membership. One of the case recently I came across is for Auditing purpose.

In this Organization we have approximately 1600+ users and there was incomplete documentation for this scenario.

There was no other way than writing small PowerShell script.

SCAP-0284
Note: There might be some other ways as well to script and accomplish this task.

Even though this script does not make any changes to your environment, its a good practice to use the script in test environment before you run in production.

$Report = @()

#Collect all users
$Users = Get-ADUser -Filter * -Properties Name, GivenName, SurName, SamAccountName, UserPrincipalName, MemberOf, Enabled -ResultSetSize $Null

# Use ForEach loop, as we need group membership for every account that is collected.
# MemberOf property of User object has the list of groups and is available in DN format.
Foreach($User in $users){
$UserGroupCollection = $User.MemberOf
#This Array will hold Group Names to which the user belongs.
$UserGroupMembership = @()
#To get the Group Names from DN format we will again use Foreach loop to query every DN and retrieve the Name property of Group.
Foreach($UserGroup in $UserGroupCollection){
$GroupDetails = Get-ADGroup -Identity $UserGroup
#Here we will add each group Name to UserGroupMembership array
$UserGroupMembership += $GroupDetails.Name
}

#As the UserGroupMembership is array we need to join element with ‘,’ as the seperator
$Groups = $UserGroupMembership -join ‘, ‘

#Creating custom objects

$Out = New-Object PSObject
$Out | Add-Member -MemberType noteproperty -Name Name -Value $User.Name
$Out | Add-Member -MemberType noteproperty -Name UserName -Value $User.SamAccountName
$Out | Add-Member -MemberType noteproperty -Name Status -Value $User.Enabled
$Out | Add-Member -MemberType noteproperty -Name Groups -Value $Groups
$Report += $Out
}

#Output to screen as well as csv file.

$Report | Sort-Object Name | FT -AutoSize
$Report | Sort-Object Name | Export-Csv -Path ‘d:\UserGroupMembership-Report.csv’ -NoTypeInformation

 

Hope this helps.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s