Home > Back-end >  Get-ADGroupmember with two Groups
Get-ADGroupmember with two Groups

Time:12-23

I have two AD groups and would like to extract their member. I can run the script if I specify one group. When I put a second group it is impossible for me to generate two different reports. Can you help me?

$ADGroup= "Group_Test","Group_Test_ABC"
$Group = Get-ADGroupMember -Identity $ADGroup | ? {$_.objectclass -eq "user"}
$Path = "C:\Temp\$ADGroup $((Get-Date).ToString("(yyyy-MM-dd)")).xlsx"

$Result =
foreach ($User in $Group) {
    Get-ADUser -Identity $User -Properties * | Select @{n='ADGROUP NAME';e={$ADGroup}}, @{n="DisplayName";e={$_.DisplayName}}, @{n='SamAccountName';e={$_.SamAccountName}}, @{n='UPN';e={$_.UserPrincipalName}}
}

$Result | Export-Excel -Path $Path

CodePudding user response:

Get-ADGroupMember only takes one group as input, if you need to query more than one you would need to loop over the groups:

$ADGroup = "Group_Test", "Group_Test_ABC"
$result = foreach($group in $ADGroup)
{
    $members = Get-ADGroupMember -Identity $group | Where-Object {
        $_.objectclass -eq "user"
    }

    foreach($member in $members)
    {
        $user = Get-ADUser $member -Properties DisplayName

        [pscustomobject]@{
            'ADGROUP NAME'    = $group
            DisplayName       = $user.DisplayName
            SamAccountName    = $user.SamAccountName
            UserPrincipalName = $user.UserPrincipalName
        }
    }
}

$Path = "C:\Temp\$ADGroup $((Get-Date).ToString("(yyyy-MM-dd)")).xlsx"
$Result | Export-Excel -Path $Path

There is a different alternative to above approach, more efficient one but it would only find those users that exists on the current Domain, if there were members (users) on different Domains this would not find them.

$result = foreach($group in $ADGroup)
{
    $thisGroup = Get-ADGroup $group
    $splat = @{
        LDAPFilter = "(memberOf=$($thisGroup.DistinguishedName))"
        Properties = 'DisplayName'
    }
    $users = Get-ADUser @splat
    foreach($user in $users)
    {
        [pscustomobject]@{
            'ADGROUP NAME'    = $thisGroup.SamAccountName
            DisplayName       = $user.DisplayName
            SamAccountName    = $user.SamAccountName
            UserPrincipalName = $user.UserPrincipalName
        }
    }
}
  • Related