Powershell – list group membership for AD users
With two levels nested group memberships…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# cls $outfile = 'c:\temp\some_users-' + (Get-Date -Format yyyy-MM-dd_hh-mm-ss) + '.txt' "User name" + ";" + "Initials" + ";" + "userAccountControl" + ";" + "Department name" + ";" + "Group name" + ";" + "Group DN" + ";" + "Group category" + ";" + "Description" + ";" + "ManagedBy" + ";" + "Sub group of"| Out-File -FilePath $outfile -Append -Force $users = Get-ADUser -SearchBase “OU=some_OU,dc=some_domain,dc=com” -Filter * -ResultSetSize 5000 -Properties Department,userAccountControl foreach ($user in $Users) { $groups = Get-ADPrincipalGroupMembership $user.SamAccountName foreach ($group in $groups) { $ADgroup = Get-ADGroup -Identity $group.SID.value -Properties Description,ManagedBy,Members,ObjectCategory,GroupCategory,GroupScope $string = "$($user.name);$($user.SamAccountName);$($user.userAccountControl);$($user.Department);$($ADgroup.name);$($ADgroup.DistinguishedName);$($ADgroup.GroupCategory);$($ADgroup.Description);$($ADgroup.ManagedBy);N/A" $string | Out-File -FilePath $outfile -Append -Force $SUBgroups1 = Get-ADPrincipalGroupMembership $group.SamAccountName foreach ($SUBgroup1 in $SUBgroups1) { $ADSUBgroup1 = Get-ADGroup -Identity $SUBgroup1.SID.value -Properties Description,ManagedBy,Members,ObjectCategory,GroupCategory,GroupScope $string = "$($user.name);$($user.SamAccountName);$($user.userAccountControl);$($user.Department);$($ADSUBgroup1.name);$($ADSUBgroup1.DistinguishedName);$($ADSUBgroup1.GroupCategory);$($ADSUBgroup1.Description);$($ADSUBgroup1.ManagedBy);$($ADgroup.name)" $string | Out-File -FilePath $outfile -Append -Force $SUBgroups2 = Get-ADPrincipalGroupMembership $SUBgroup1.SamAccountName foreach ($SUBgroup2 in $SUBgroups2) { $ADSUBgroup2 = Get-ADGroup -Identity $SUBgroup2.SID.value -Properties Description,ManagedBy,Members,ObjectCategory,GroupCategory,GroupScope $string = "$($user.name);$($user.SamAccountName);$($user.userAccountControl);$($user.Department);$($ADSUBgroup2.name);$($ADSUBgroup2.DistinguishedName);$($ADSUBgroup2.GroupCategory);$($ADSUBgroup2.Description);$($ADSUBgroup2.ManagedBy);$($ADSUBgroup1.name)" $string | Out-File -FilePath $outfile -Append -Force } } } } |