Powershell – Exporting All Groups and Group Members from Active Directory

active-directorygroupspowershellscripting

I am relatively new to powershell and am trying to get a list of all groups in the domain with their respective members. Here's what I'm working with now:

Import-Module ActiveDirectory
$OutPutFile = New-Item -type file -force "AllGroups.txt"

#Filters for Groups

# 2 Global distribution group
# 4 Domain local distribution group
# 8 Universal distribution group
# -2147483646 Global security group
# -2147483644 Domain local security group
# -2147483640 Universal security group

$D = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$Domain = [ADSI]"LDAP://$D"
$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.PageSize  = 10000

$Searcher.Filter = "(&(objectCategory=Group)(|(groupType=2)(groupType=4)(groupType=8)))"
$Searcher.SearchRoot = "LDAP://" + $Domain.Name

$Results = $Searcher.FindAll()
foreach ($Result in $Results)
{
    $Item = $Result.Properties

    foreach ($Member in $Item.member) 
    {
    $Name = Get-ADUser "$Member" -Properties DisplayName | select -expand displayname
    $Item.cn, "$Name" | Out-File $OutPutFile -encoding ASCII -append
    }
}

I'd like the output to be Group;Displayname or Group-Displayname (so I can put it in Excel and format from there) however I cannot seem to get output in the same line. The output currently comes out like this:

Group
DisplayName
Group
DisplayName

What am I doing wrong or how can I adjust the code to give me the two items on the same line? I was also thinking about adding in the OU the groups are in but haven't had luck finding a way to get that from my results.

Best Answer

When you pipe a list to Out-File -Append, it'll write each entry to a new line.

Instead, construct a string from the two values and pipe that:

$MemberLine = '"{0}","{1}"' -f $Item.CN,$Name 
$MemberLine | Out-File $OutPutFile -encoding ASCII -append

Alternatively, use Export-Csv, it'll take care of comma-separating the values correctly:

$Members = foreach ($Result in $Results)
{
    $Item = $Result.Properties

    foreach ($Member in $Item.member) 
    {
        Get-ADUser "$Member" -Properties DisplayName |Select @{Name='Group';Expression={$Item.CN}},@{Name='Member',Expression={$_.displayname}}
    }
}
$Members | Export-Csv $OutPutFile -Encoding ASCII -NoTypeInformation

As already mentioned, you can replace your [adsisearcher] with the Get-ADGroup cmdlet, much more concise:

$Groups = Get-ADGroup -Filter {GroupCategory -eq 'Distribution'}
$Groups | ForEach-Object {
  $Group = $_
  $Group.Member |ForEach-Object {
    Get-ADUser $_ -Properties displayName
  } | Select @{N='Group';E={$Group.Name}},@{N='Member';E={$_.displayName}}
} | Export-Csv $OutPutFile -Encoding ASCII -NoTypeInformation