If you sometimes have to find a user list and get group memberships, it can be a chore. It doesn’t have to be. You too can experience a scripted approach to getting that data. This will search the AD Forest’s sub domains that you have rights to at least read to get user memberships that follow a specific pattern. Very useful when you have one domain for groups and users from many domains. Universal groups are great for that. You just need to populate the referenced “useremail.txt” file with user email addresses and deleting any white space in the file. You can also get additional information in the report by adding in the “line = “” | Select-Object” and adding additional fields and then matching the name designated with the “line.Fields = syntax.”

# Script to search domains in forest for users via user email address. You could also search via UPN by replacing EmailAddress with UserPrincipalName.
# This requires AD module, read rights to forest / domains, and user group pattern. Ran with ISE and tested on desktop / server platforms. This also uses
# the global catalog lookup as seen referenced by Get-ADUser -server domain:3268. Assistance from Notesofascripter.com in making this.
$debug      = $true
$domains    = (Get-ADForest).Domains
$date       = Get-Date -Format MMddyy
$userExists = ""
$reportName = "nameofreport.csv"
$report     = @()

$emailList  = Get-Content -Path "c:\scripts\logs\useremail.txt"

$emailSam   =  foreach($user in $emailList) {
    (Get-ADUser -server domain:3268 -f {EmailAddress -eq $user}).SamAccountName
  }

$users      = $emailSam

foreach ($domain in $domains){
    if ($debug){Write-Host $domain -ForegroundColor Cyan}
    foreach ($user in $users) {
        Try{
            $userExists = Get-ADUser $user -Server $domain -ErrorAction Stop
        }
        Catch {
            if ($debug){Write-Host "$user not found in $domain" -BackgroundColor yellow -ForegroundColor black}
            $userExists = $null
            Continue
        }
        if ($userExists -ne $null){
            if ($debug){ Write-Host "Found $user in $domain domain" -BackgroundColor Cyan -ForegroundColor Black}
            $group = $userExists | Get-ADPrincipalGroupMembership | Where-Object Name -like "GroupNamePattern*" -ErrorAction Stop
            $line          = "" | Select-Object Name, Domain, RealName, Group
            $line.Name     = $user
            $line.Domain   = $domain
            $line.RealName = $userExists.name
            $line.Group    = $group.name -join "; "
            if ($debug){ $line }
            $report       += $line
            $users         = $users -ne $user
            
        }
    }
}

$report | Export-Csv "c:\scripts\logs\$date-$reportName" -Append -NoTypeInformation