'How to get-adgroup members by their Name or SamAccountName

i would like to extract members from an AD Group that contains Members and security group.

Example, Group_A:
User1
User2
User3
Group_B

When I run my script, it shows:

CN=User1,OU=Users,DC=Contoso,DC=com CN=User2,OU=Users,DC=Contoso,DC=com CN=User3,OU=Users,DC=Contoso,DC=com CN=Group_B,OU=Users,DC=Contoso,DC=com

Is there another way to show their Name and/or SamAccountname?

$Groups = 
@"
GroupNames;
Group_A
"@ | ConvertFrom-Csv -Delimiter ';'



$ADGroups = 
Foreach ($Group in $Groups){ 
Get-ADGroup $Group.GroupNames -Server contoso.com -Properties Members }

$ADGroups.Members


Solution 1:[1]

Get-ADGroupMember has two parameters you can use for that. samaccountname, and name.

Simply do the following:

Get-ADGroupMember -identity $ADGroup | select-object SamAccountName, Name

Or in your code snippet:

Foreach ($group in $groups) {
Get-AdGroup -identity $group | select-object Samaccountname, Name }

Of course you could add:

Get-AdGroup -identity $group | select-object Samaccountname, Name | export-csv C:\mypath\report.csv

Solution 2:[2]

You could run a query against the returned values using Get-ADObject since it accepts DistinguishedNames as a value and isn't limited by object class:

foreach ($Group in $Groups)
{ 
    (Get-ADGroup $Group.GroupNames -Server contoso.com -Properties Members).Members | 
        ForEach-Object -Process {
            Get-ADObject -Identity $_ -Properties DisplayName | Select-Object -Property DisplayName
        }     
}

...or, you can split the results at the desired entry:

foreach ($Group in $Groups)
{ 
    (Get-ADGroup $Group.GroupNames -Server contoso.com -Properties Members).Members | 
        ForEach-Object -Process {
            $_.Split(',',2).Split("=")[1]
        }     
}

Disclaimer: I don't have the AD Module installed on my system so I can't confirm if this is all that is needed.

Solution 3:[3]

The easiest way would be to expand the members property and in Get-ADGroup and then pipe it to Get-ADUser

$adUsers = Foreach ($Group in $Groups) {
    Get-ADGroup $Group.GroupNames -Server contoso.com -Properties Members | Select-Object -ExpandProperty Members | Get-aduser
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bowshock
Solution 2 Abraham Zinala
Solution 3 Brandon Spell