0

I have a list of users and I need to know what their Active Directory Group memberships are. I need them to group together in a csv something like this with the username, groupname, and grouptype (Security of Distribution) but I'm not having much luck. Below is the Powershell script I tried to make up and use.

$Users = Get-Content -Path 'C:\Scripts\Lists\UserDistro.txt'

Foreach ($user in $users) {

$GroupName = Get-ADPrincipalGroupMembership $user | Select-Object -Property Name
$GroupType = Get-ADPrincipalGroupMembership $user | Select-Object -Property GroupCategory

$Results = @{'Username'=$User;'Group'=$GroupType}

$obj = New-Object -TypeName PSObject -Property $Results
Write-Output $Obj | Format-table -AutoSize

The output I'm getting looks like this:

Username Group                                                                                         GroupType                                                                              
-------- -----                                                                                         ---------                                                                              
psmith  {@{Name=Domain Users}, @{Name=Group1}, @{Name=Group2}, @{Name=Group3:}...} {@{GroupCategory=Security}, @{GroupCategory=Security}, @{GroupCategory=Security}, @{...

The issues I'm having are

  • The list is truncated, there should be more groups than what's showing here
  • I don't need all this peripheral information @{Name= Just the group name
  • How can I sort this so the group name and group type lineup?
woftt69
  • 1
  • 1
  • 1

1 Answers1

0

I dislike Get-ADPrincipalGroupMembership so, this is what I would personally use:

$Users = Get-Content -Path 'C:\Scripts\Lists\UserDistro.txt'

$result = foreach($user in $users)
{
    $adUsr = Get-ADUser $user
    $membership = Get-ADGroup -LDAPFilter "(member=$($user.DistinguishedName))"
    
    foreach($group in $membership)
    {
        [pscustomobject]@{
            User = $adUsr.samAccountName
            GroupName = $group.Name
            GroupType = $group.GroupCategory
        }
    }
}

$result | Format-Table -AutoSize

Using Get-ADPrincipalGroupMembership would look like this:

$Users = Get-Content -Path 'C:\Scripts\Lists\UserDistro.txt'

$result = foreach($user in $users)
{
    $membership = Get-ADPrincipalGroupMembership $user
    
    foreach($group in $membership)
    {
        [pscustomobject]@{
            User = $user
            GroupName = $group.Name
            GroupType = $group.GroupCategory
        }
    }
}

$result | Format-Table -AutoSize

Or with Select-Object:

$Users = Get-Content -Path 'C:\Scripts\Lists\UserDistro.txt'

$result = foreach($user in $users)
{
    Get-ADPrincipalGroupMembership $user |
    Select-Object @{n='User';e={$user}},
                  @{n='GroupName';e={$_.Name}},
                  @{n='GroupType';e={$_.GroupCategory}}
}

$result | Format-Table -AutoSize
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37