Home > Software design >  Export AD members from specific AD groups
Export AD members from specific AD groups

Time:01-15

I want to retrieve the SamAccountName from a number of ~600 AD groups that end with a certain string.

For example:

AD Groups:
AAA-BBB-XXX
CCC-DDD-XXX
EEE-FFF-XXX

Now I want to get the SamAccountName of all AD groups that end with XXX but also, with a relation between SamAccountName and AD-group so that I know to which AD-group they belong. So:

SamAccountName | AD GROUP
------------------------------
Bernie.Sanders | AAA-BBB-XXX
Donald.Trump  | AAA-BBB-XXX
Barack.Obama  | AAA-BBB-XXX
Joe.Biden     | CCC-DDD-XXX

I have managed exporting all XXX AD-groups to .csv with -like and -filter operator. I have managed exporting all SamAccountName using Get-ADGroupMember and -identity operator.

But, I'm not able (yet) to create the above list as I'm a PS newbie. I'm looking for some 'where' statement and require some guidance.

Thanks

CodePudding user response:

For this you can use a calculated property with Select-Object to combine the "AD Group Members" with the "AD Group Name". For filtering the groups that matches your condition, in this case, ending with XXX you can use the -LDAPFilter or -Filter from Get-ADGroup cmdlet.

$filter = "(samAccountName=*XXX)" # => Ends with XXX

$result = foreach($group in Get-ADGroup -LDAPFilter $filter)
{
   # Here all groups ending with XXX are being enumerated

   Get-ADGroupMember $group | Select-Object @{
      Name = 'ADGroup'
      Expression = { $group.samAccountName }
   }, samAccountName, ObjectClass
}

$result | Export-Csv .... 

Note that, AD Groups can have members that are not only users, if you wanted to the group members where their class is "User" you could add Where-Object or .Where() method:

Get-ADGroupMember $group |
    Where-Object { $_.ObjectClass -eq 'user' } |
    Select-Object ....
(Get-ADGroupMember $group).Where({
    $_.ObjectClass -eq 'user'
}) | Select-Object ....
  •  Tags:  
  • Related