PowerShell Script to get members from two different AD Groups

Welcome Forums General PowerShell Q&A PowerShell Script to get members from two different AD Groups

This topic contains 3 replies, has 2 voices, and was last updated by

1 year, 7 months ago.

  • Author
  • #77313

    Points: 0
    Rank: Member

    I need to create a powershell script that will get the members of two specific AD groups and format them in a nice to read Excel/csv file.

    The output includes AD Group Name, Description, and Members. I can get the information by running these individually:
    Get-ADGroupMember "domain admins" |select name |out-file d:\domain-admins.csv
    Get-ADGroupMember "security_admin_group" |select name |out-file d:\security_admin_group.csv

    I was looking around the Internets and this looked like it would work but I am not retrieving the AD group name or Description.
    $groups = Get-ADGroup "Domain Admins"
    $output = ForEach ($g in $groups)
    $results = Get-ADGroupMember -Identity $g.name -Recursive | Get-ADUser -Properties displayname, objectclass, name

    ForEach ($r in $results){
    New-Object PSObject -Property @{
    GroupName = $g.Name
    Username = $r.name
    ObjectClass = $r.objectclass
    DisplayName = $r.displayname
    $output | Export-Csv -path C:\scripts\SecurityGroups.csv

    And it is only getting one AD group. Not sure how to make it run again for the other group.

  • #77316

    Points: 0
    Rank: Member

    I found this one which does the job.

    $groups = Get-Content C:\Scripts\grouplist.txt

    $results = foreach ($group in $groups) {
    Get-ADGroupMember $group | select samaccountname, name, @{n='GroupName';e={$group}}, @{n='Description';e={(Get-ADGroup $group -Properties description).description}}


    $results | Export-csv C:\Scripts\SecurityGroups.csv -NoTypeInformation

    • #77329

      Points: 1,086
      Helping Hand
      Rank: Community Hero

      Depending on the amount of members in your groups your query would probably speed up a little when you do it like this:

      $GroupList = Get-Content C:\Scripts\grouplist.txt
      $Results = foreach ($Group in $GroupList) {
      $Description = Get-ADGroup -Identity $Group -Properties Description | Select-Object -ExpandProperty Description
      Get-ADGroupMember -Identity $Group | 
          Select-Object -Property SamAccountName, Name, @{Name='GroupName';Expression={$Group}}, @{Name='Description';Expression={$Description}}
      $Results | Export-csv -Path C:\Scripts\SecurityGroups.csv -NoTypeInformation

      This way you don't need to query the description of the group again and again and again .... 😉

  • #77358

    Points: 0
    Rank: Member

    Excellent! Thanks for the suggestion.

The topic ‘PowerShell Script to get members from two different AD Groups’ is closed to new replies.