Loading Now

Use Powershell to output a list of users’ group membership to csv

active directory group membership output csv example

Here is a quick and easy script for getting a list users group membership. Before we begin, if you need to know how to connect to Active Directory using powershell see this post. The idea is you feed a CSV file into the script that has a list of usernames in one columns like this:

Screenshot_20200918_142951 Use Powershell to output a list of users' group membership to csv
Example of what the input csv file should look like

After you run the script you will get an output csv file that looks like this:

Screenshot_20200921_084632 Use Powershell to output a list of users' group membership to csv
Example of output file

That’s pretty much it, here is the script:


#Set input file path
$inputcsv = "C:\ps\users.csv"
#Set output file path
$outputcsv = "C:\ps\out.csv"
#Clears file
"name,group" | Out-File $outputcsv

#import csv file
$list = Import-Csv -Path $inputcsv

#Start Loop
foreach ($user in $list) {
    #Set username veriable
    $username = $user.name
    #Get groups that the user is a member of
    $groups = Get-ADPrincipalGroupMembership $username | select -ExpandProperty name 

    #Secondary loop to output results
    foreach ($group in $groups) {
        #Output username and group in one line to output csv
        "$username,$group" | out-file $outputcsv -Append
    }    
}

My name is Skylar Pearce, I have been working as a System Administror since 2013 as well some side consulting work. During my career I have worked with everything from Active Directory and vCenter to configuring routers and switches and phone systems, documenting and scripting my way through the whole thing. I have a Security+ certification and am currently working on my PenTest+. Throughout my career I have gained almost all of my knowledge from blogs like this. It is now time for me to pay it back. Over time I have gathered scripts and tricks over the years that I will share on this site. A lot of the posts here will be mainly reference posts, some will be full on how to’s. I am happy to go into more depth on any other topics I go over here, just make a comment on a post. I will do my best to post once a day on weekdays but as I run out of ideas it may slow down. My WordPress skills are still growing so the site will likely get better over time as I learn. You can reach me at contact@allthesystems.com or on LinkedIn