I need to find AD group members from given groups in csv file as input. the groups contains Users and Groups also. below is sample input data
I wrote the below code. for users I am getting the output (i.e. for the first entry), but for the second one, as they are groups within group, I am not able to fetch the email.
$GroupCollection= Import-csv -Path "C:\Groups.csv" $Report = @() Foreach($Group in $GroupCollection){ $MemberGroup=@() $Group = $Group.'OPE DLs' if($Group -match '@') { $pos = $Group.IndexOf("@") $leftPart = $Group.Substring(0, $pos) } else { $leftPart = $Group } $MemberGroup = Get-ADGroupMember -identity $leftPart -recursive | Get-ADUser -Properties mail | Select-Object mail $MemberGroups = ($MemberGroup.mail) -join "`r`n" if($MemberGroups -ne ""){ $Out = New-Object PSObject $Out | Add-Member -MemberType noteproperty -Name 'Contract Details' -Value $Group.'Customer subset' $Out | Add-Member -MemberType noteproperty -Name 'Group Name' -Value $leftPart $Out | Add-Member -MemberType noteproperty -Name 'Member Groups' -Value $MemberGroups $Report += $Out } } $Report | Sort-Object Name | FT -AutoSize $Report | Sort-Object Name | Export-Csv -Path ‘C:\Group-MemberGroups-Report.csv’ -NoTypeInformation Please let me know how to get the details. Is the approach is fine or there is any other way to do this.
expected output


Get-ADGroupMemberreturned. IfobjectClass -eq 'user'then doGet-ADUser, elseifobjectClass -eq 'group'then useGet-ADGroup. ifobjectClass -eq 'computer'then don't do anything