Public/Get-ADGroupMembersFromCsv.ps1
<#
.SYNOPSIS Generates membership reports for Active Directory groups specified in a CSV file. .DESCRIPTION This function reads a CSV file containing group names (possibly multiple per row) and retrieves all members of each group from Active Directory. The report includes user names, email addresses, and group information, and is saved to a separate CSV file per group. .PARAMETER CsvFile Path to the input CSV file containing the group names. .PARAMETER ColumnName The column name in the CSV that contains group names (can be comma-separated). .PARAMETER LabelPrefix Prefix to be used in the exported file name. .PARAMETER LogLocation Optional directory where export CSVs will be saved (defaults to user profile path). .PARAMETER Domains An array of AD domains to search across for group members. .OUTPUTS Exports CSV files for each group listing its members and their details. .EXAMPLE Get-ADGroupMembersFromCsv -CsvFile "groups.csv" -ColumnName "DLNames" -LabelPrefix "GroupReport" -Domains @("corp.local", "test.corp.local") #> function Get-ADGroupMembersFromCsv { param ( [Parameter(Mandatory = $true)] [string]$CsvFile, [Parameter(Mandatory = $true)] [string]$ColumnName, [Parameter(Mandatory = $true)] [string]$LabelPrefix, [Parameter(Mandatory = $false)] [string]$LogLocation = $env:USERPROFILE, [Parameter(Mandatory = $true)] [string[]]$Domains # e.g., @('emea.thermo.com','amer.thermo.com','apac.thermo.com') ) $label = Get-Date -Format "yyyyMMdd" try { # Step 1: Load CSV and flatten any comma-separated values in target column $InputFile = Import-Csv -Path $CsvFile | Select-Object -Property $ColumnName -Unique $flatGroups = [System.Collections.ArrayList]@() foreach ($line in $InputFile) { $value = $line.$ColumnName if ($value) { foreach ($item in $value -split ',') { $trimmed = $item.Trim() if ($trimmed -ne '') { $null = $flatGroups.Add($trimmed) } } } } $uniqueGroups = $flatGroups | Sort-Object -Unique foreach ($group in $uniqueGroups) { $exportPath = Join-Path $LogLocation "$LabelPrefix`_$group`_$label.csv" $results = @() $members = ADGroupVerify -GroupName $group -Domains $Domains if (-not $members) { New-Item $exportPath -ItemType File -Force | Out-Null continue } foreach ($m in $members.Members) { $results += [pscustomobject]@{ Name = Get-CommonNameFromDN -DN $m SamAccountName = Get-SamAccountNameFromDN -DN $m EmailAddress = Get-MailFromDN -DN $m Group = $group #UserDomain = $m.UserDomain } } $results | Export-Csv -Path $exportPath -NoTypeInformation -Encoding UTF8 } return "Success" } catch { Write-Error "ERROR: $($_.Exception.Message)" } } |