0
Follow
0
View

Get-ADGroupmember with two Groups

cs9_11 注册会员
2023-01-25 06:58

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
        }
    }
}