Get a list of user and there Group Membership

This is how to get an CSV file, including user_SamAccountName;User_FullName;group1;group2;group3, etc

It posible to remove the comment before break, and then break the export after 5 user, to see that it function well.

It will first write it output at the ending of the script, so terminate it, will result in an empty file.

$user_count = 0
$output = ""
$OFS = "`r`n"
$users = Get-ADUser -Filter * -SearchBase "DC=dalbjerg,DC=local" | SELECT Name,samaccountname

foreach($user in $users) {
    #echo $user.SamAccountName
    $username = $user.SamAccountName
    $output += $username + ";" + $user.name + ";"
    $groups = Get-ADPrincipalGroupMembership $user.Samaccountname | select name
        foreach($group in $groups) {
            $output += $group.name + ";"
        }
    $output += $OFS
    $output += $OFS
    $user_count += 1
    if($user_count -eq 5) {
        #break
    }
}
Write-Output $output | out-file C:\temp\export.csv

 

Leave a Reply

Your email address will not be published. Required fields are marked *