Hello Spice Team,

I am trying to get all the AD group memberships that a list of users. Here is the code that I have created so far. The only problem is I can see is that I get Membership names but not whos that membership belongs too.

$names = "jsmith", "ajohnson"

forEach($names in $names)
{
 Get-adprincipalgroupmembership -Identity $names | select name, samaccountname

}
2 Spice ups

Welcome

If you post code, please use the ‘Insert Code’ button. Please and thank you!

codebutton_small.png

you can try something like so:

$names = "jsmith", "ajohnson"
forEach ($name in $names){
    $membership = Get-adprincipalgroupmembership -Identity $name | select name, samaccountname
    [pscustomobject]@{
        UserName            = $name
        GroupName           = ($membership.name) -join ','
        GroupSamAccountname = ($membership.samaccountname) -join ','
    }
}
1 Spice up

or if you want it a bit cleaner like so

$names = "jsmith", "ajohnson"
$Report = 
forEach ($name in $names){
    $membership = Get-adprincipalgroupmembership -Identity $name | select name, samaccountname
    foreach ($grp in $membership) {
        [pscustomobject]@{
            UserName            = $name
            GroupName           = $grp.name
            GroupSamAccountname = $grp.samaccountname
        }
    }
}
$report 
$report | export-csv ".\GroupMembershipReport.csv" -NoTypInformation
1 Spice up

Thank you @alexw ​ they both worked wonderfully.

I was looking for something similar to this but is there a way to filter by certain group names as well, instead of all the group names?

Get-ADPrincipalGroupMembership USER_NAME | Where-Object { $_.name -like "AD_GEOUP_NAME" } | select name

Are you looking for something like this? Or do you want to create an array and store the ad group names in there?