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

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:

Example of what the input csv file should look like
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:

Example of output file
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
    }    
}
Tagged : /