Is it possible to change the PS script below in two ways:
I would like to see this result, see the photo below please:
cls
$Groups = "Group1", "Group2", "Group3"
$results = foreach ($Group in $Groups) {
Get-ADGroupMember -Server contoso.com $group |
select SamAccountName, @{n='GroupName';e={$group}}, @{n='Description';e={(Get-ADGroup $group -Properties description).description}}
}
$results
$results | Export-csv C:\TEMP\GroupMemberShip.CSV -NoTypeInformation
With some minor changes to your original code, you could first gather the wanted info per group and before exporting to CSV, use Group-Object
to merge the details.
Something like:
$Groups = "Group1", "Group2", "Group3"
$results = foreach ($Group in $Groups) {
$adGroup = Get-ADGroup $group -Properties Description -ErrorAction SilentlyContinue
if ($adGroup) {
$adGroup | Get-ADGroupMember -Server 'contoso.com' |
Select-Object SamAccountName,
@{Name = 'GroupName'; Expression = {$adGroup.Name}},
@{Name = 'Description'; Expression = {$adGroup.Description}}
}
else {
Write-Warning "Group '$group' could not be found.."
}
}
# now group the results on the GroupName property and
# return objects with joined SamAccountNames and Descriptions
$results | Group-Object GroupName | ForEach-Object {
[PsCustomObject]@{
SamAccountName = ($_.Group.SamAccountName | Sort-Object -Unique) -join ', '
GroupName = $_.Name
Description = ($_.Group.Description | Sort-Object -Unique) -join ', '
}
} | Export-Csv -Path 'C:\TEMP\GroupMemberShip.CSV' -NoTypeInformation
Although I don't understand why you would like to have duplicate items in your output, you can do this like below
$Groups = "Group1", "Group2", "Group3", "Group2", "Group3"
$results = foreach ($Group in $Groups) {
$adGroup = Get-ADGroup $group -Properties Description -ErrorAction SilentlyContinue
if ($adGroup) {
$adGroup | Get-ADGroupMember -Server 'contoso.com' |
Select-Object @{Name = 'SamAccountName'; Expression = {($_.SamAccountName | Sort-Object -Unique) -join ', '}},
@{Name = 'GroupName'; Expression = {$adGroup.Name}},
@{Name = 'Description'; Expression = {$adGroup.Description}} -ExcludeProperty SamAccountName
}
else {
Write-Warning "Group '$group' could not be found.."
}
}
$results | Sort-Object GroupName | Export-Csv -Path 'C:\TEMP\GroupMemberShip.CSV' -NoTypeInformation