List All Groups and Their Members with PowerShell on Win2008r2

Gimme the codes! powers, activate!

$Groups = Get-ADGroup -Properties * -Filter * -SearchBase "OU=Groups,DC=corp,DC=ourcompany,DC=Com" 
Foreach($G In $Groups)
{
    Write-Host $G.Name
    Write-Host "-------------"
    $G.Members
}

The point being, just take your time and break it out into steps. I know that it's fun to try to get everything and the kitchen sink to fit into a one-liner with Powershell, but it's by no means required.

A few notes:

  • You don't need to do Get-ADGroupMember if you collect the Members property in the initial Get-ADGroup Cmdlet. The good thing about this is that it halves the amount of calls you have to make to AD, which should make your script run faster, and it eases the burden on the domain controller.

  • $G.Members will display all members of the group $G... in Powershell 3. In Powershell 2, you might still need to put another Foreach inside the Foreach there to enumerate through the group members. (Yo dawg, I heard you like loops...)

  • I use Write-Host here, which is gross. You should never really use Write-Host. Instead, you should be building and outputting objects, not text, but that was a whole other topic and I was too lazy to do that for this answer.


Here is a much better solution. This will put everything in a 3 column csv with group name, username, and sam account name. A lot easier to figure out what group someone is in when there's 400 users in a group as you don't have to scroll.

Import-Module ActiveDirectory

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

$Table = @()

$Record = @{
  "Group Name" = ""
  "Name" = ""
  "Username" = ""
}


Foreach ($Group in $Groups) {

  $Arrayofmembers = Get-ADGroupMember -identity $Group -recursive | 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