PowerShell Script to get members from two different AD Groups

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.
Clear-Host
$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.

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

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

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

$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 … :wink:

Excellent! Thanks for the suggestion.