PowerShell script to return members of multiple security groups

9

I need to return all members of multiple security groups using PowerShell. Handily, all of the groups start with the same letters.

I can return a list of all the relevant security groups using the following code:

Get-ADGroup -filter 'Name -like"ABC*"' | Select-Object Name

And I know I can return the membership list of a specific security group using the following code:

Get-ADGroupMember "Security Group Name" -recursive | Select-Object Name

However, I can't seem to put them together, although I think what I'm after should look something like this (please feel free to correct me, that's why I'm here!):

$Groups = Get-ADGroup -filter 'Name -like"ABC*"' | Select-Object Name
ForEach ($Group in $Groups) {Get-ADGroupMember -$Group -recursive | Select-Object Name

Any ideas on how to properly structure that would be appreciated!

Thanks,

Chris

This question is tagged with powershell active-directory

~ Asked on 2013-06-19 15:55:23

The Best Answer is


9

This is cleaner and will put in a csv.

Import-Module ActiveDirectory

$Groups = (Get-AdGroup -filter * | Where {$_.name -like "**"} | select name -expandproperty name)


$Table = @()

$Record = [ordered]@{
"Group Name" = ""
"Name" = ""
"Username" = ""
}



Foreach ($Group in $Groups)
{

$Arrayofmembers = Get-ADGroupMember -identity $Group | select name,samaccountname

foreach ($Member in $Arrayofmembers)
{
$Record."Group Name" = $Group
$Record."Name" = $Member.name
$Record."UserName" = $Member.samaccountname
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord

}

}

$Table | export-csv "C:\temp\SecurityGroups.csv" -NoTypeInformation

~ Answered on 2015-01-05 23:43:57


4

Get-ADGroupMember "Group1" -recursive | Select-Object Name | Export-Csv c:\path\Groups.csv

I got this to work for me... I would assume that you could put "Group1, Group2, etc." or try a wildcard. I did pre-load AD into PowerShell before hand:

Get-Module -ListAvailable | Import-Module

~ Answered on 2014-11-24 17:19:49


Most Viewed Questions: