Search code examples
powershellactive-directory

Why is Get-ADUser -Identity $AD_ID -Properties memberof missing one AD group?


Can the script#1 be fixed to correctly show all the AD groups for users, similar to script#2 ?

The script#1 display only one AD group:

$AD_ID="YOUR AD SAM"
$AD_user=Get-ADUser -Identity $AD_ID  -Properties memberof
$AD_groups=($AD_user.memberof | % { (Get-ADGroup $_).Name; }) -join ';';
$AD_groups.Count
$AD_groups

==== Result for above script ======

1
DM

However, The script#2 correctly displays all the AD groups :

$AD_ID="YOUR AD SAM"
$AD_groups=Get-ADPrincipalGroupMembership -Identity $AD_ID | sort name
$AD_groups.Count
$Groups_In_String=";"
$GroupSize=$AD_groups.Count-1
for ($j=0;$j -le $GroupSize; $j++)
{ $Groups_In_String=$Groups_In_String+$AD_groups.Item($j).name+";"}
$Groups_In_String

====== Result for above script ======

2
;DM;Domain Users;

I would like to learn why script#1 cannot produce the same result as script#2


Solution

  • As explained in comments, the reason for the Count discrepancy between Get-ADPrincipalGroupMembership and .MemberOf is because the .MemberOf collection will not contain the user's PrimaryGroup (usually Domain Users).

    So, if you want to use the first approach in your code you could simply query the user's PrimaryGroup in addition to MemberOf and then concatenate the values, however you should note that this approach will fail as soon as the user is a member of a group in a different domain.

    $AD_ID = 'YOUR AD SAM'
    $AD_user = Get-ADUser -Identity $AD_ID -Properties Memberof, PrimaryGroup
    $AD_groups = ($AD_user.MemberOf + $AD_user.PrimaryGroup | Get-ADGroup).Name -join ';'
    $AD_groups.Count
    $AD_groups