Get a User’s Group Memberships
Simple script came across this week at Spiceworks. The funny thing was, the script didn’t solve the OP’s problem in the slightest! Turns out he was looking for a script to list several groups and who are members of it. Still, I think this request was interesting and wanted to write a little about it.
Simple Script Goes Big
One thing the OP wanted–or so I thought at the time–was not just a listing of the groups the user is a member of, but a list using the friendly name of the group. Turns out I had already done this for myself several months earlier:
get-aduser username -property MemberOf | % {$_.MemberOf | Get-AdGroup | select Name | sort name}
As I’ve mentioned before, I don’t usually use alias’ when coding Powershell, but when I’m doing a one-liner to just get a task done I will use them. I’m also not as picky about using the proper case!
Works great but I wanted to take it to the next level. How about doing the same thing, but sorting the output so it’s a little easier to read?
$User = "thesurlyadmin" $UN = Get-ADUser $User -Properties MemberOf $Groups = ForEach ($Group in ($UN.MemberOf)) { (Get-ADGroup $Group).Name } $Groups = $Groups | Sort ForEach ($Group in $Groups) { New-Object PSObject -Property @{ Name = $UN.Name Group = $Group } }
We use the ForEach method to build our initial array, $Groups, and then simply sort the list. After that we’ll output the information as an array of objects so you can use the output any way you want to.
But it’s still not the way I want this. I prefer to use Parameters to input data into the script, because you shouldn’t have to edit the script every time you want to find out a user’s group memberships! So it’s time to break out our Advanced Functions techniques and pretty this script up.
Param ( [Parameter(Mandatory=$true,ValueFromPipeLine=$true)] [Alias("ID","Users")] [string[]]$User ) Begin { Try { Import-Module ActiveDirectory -ErrorAction Stop } Catch { Write-Host "Unable to load Active Directory module, is RSAT installed?"; Break } } Process { ForEach ($U in $User) { $UN = Get-ADUser $U -Properties MemberOf $Groups = ForEach ($Group in ($UN.MemberOf)) { (Get-ADGroup $Group).Name } $Groups = $Groups | Sort ForEach ($Group in $Groups) { New-Object PSObject -Property @{ Name = $UN.Name Group = $Group } } } }
There, now we have a nice self-contained script that you can input a user’s name–or multiple names–and get a sorted report of their group memberships. Also configured the script to accept pipeline input so you can pipe the values from Get-Content into the script.
Here’s a sample of the output:
Is there a way to modify this script to create a .csv file that would show the groups for all active users in the domain?
You could do the following.
Get-ADUser -Filter {enabled -eq ‘true’} -ResultSetSize $null | Get-UserGroupMembership | Export-Csv -NoTypeInformation UserGroupMembership.csv
Regards,
Brian
Hello Martin9700,
Thank you for putting this post together, this is exactly what I had been trying to do, but did not have the skills to quite put it together.
You’re welcome Brian! Means a lot to hear that!
Martin,
Your script has been a great starting point but I’m trying to get it to process an input file ( a .csv) created from the targets I identify with my search. if you see in the comments, it falls apart when I try to pipe the list of users to the group processing. any help would be appreciated.
## Variables
Get-Mailbox -Filter ‘((-not(CustomAttribute14 -ne $null)) -and (CustomAttribute11 -eq ”adc.fmi.com”) -and (-not(ManagedFolderMailboxPolicy -ne $null)))’|Select SamAccountName |Export-Csv d:\ps_output\Evusertag\14s.csv
$Users = Import-Csv d:\ps_output\Evusertag\14s.csv
## Right below here is where I go haywire, it won’t process the list of users that I import above.
$grps=Get-ADUser $Users -Property memberOf | Select -ExpandProperty memberOf | Get-ADGroup | Select Name
## Action
foreach($grp in $grps){if($grp.Name -match ‘SG-ADC-EV Users’){set-mailbox $users -customattribute14 ‘EVP-RP’} elseif ($grp.Name -notmatch ‘SG-ADC-EV Users’){get-mailbox $users |select Primarysmtpaddress | Export-Csv d:\ps_output\Evusertag\ADCNonevuser.csv} }
$Nonevusers = Import-Csv d:\ps_output\Evusertag\ADCNonevuser.csv
foreach ($Nonevuser in $Nonevusers) {Get-mailbox | set-mailbox -customattribute14 ‘TEST’}
Get-Mailbox -Filter ‘((-not(CustomAttribute14 -ne $null)) -and (CustomAttribute11 -eq ”adc.fmi.com”) -and (-not(ManagedFolderMailboxPolicy -ne $null)))’|Select SamAccountName |Export-Csv d:\ps_output\Evusertag\14s.csv
$Users = Import-Csv d:\ps_output\Evusertag\14s.csv
Foreach ($user in $Users) {$grps=Get-ADUser $User -Property memberOf | Select -ExpandProperty memberOf | Get-ADGroup | Select Name
perfect. wasn’t able to modify the script to return on all users, but i solved that by doing $user = get-aduser -filter * and then exported to csv just fine.
Thanks for the script, it works like a charm!!! I’m working on an AD audit task recently, one of the requirement is to display the group type in the output. I know Get-ADPrincipalGroupMembership can show me the information but I need to work out a solution for support staff so that they can produce the report by themselves . what is the best way to only capture the output I want. for example, I only want to capture objectClass, GroupScope and GroupCategory in my output. Thanks again:)
Hello Alex,
You could add the following after Group = $Group
objectCLass = $UN.objectClass
GroupScope = $UN.GroupScope
GroupCategory = $UN.GroupCategory
If you only wanted these three columns, then you could remove the two lines above them (lines 10 & 11 in the code snippet above).
HTH
Brian
Thanks Brian for the direction, will spend some time with it:)
Hi guys,
How do I export all users’ properties? For example I have a 5 subgroup in group “A”, where 3 subgroups are blanks and 2 has members. The group “A” owner wants me to generate all the members details in group “A”.
I have tried the following individual subgroup but only gets Name, SAM Account and Object Class.
Get-ADGroupMember -identity “sub-group” | select Name,SamAccountName,ObjectClass | Export-csv -path C:\Temp\Groupmembers.csv -NoTypeInformation
Great script, but if the user account starts with a special character like ! it does not work.
Most special characters have meaning in PowerShell (like ! means “not”) so try surrounding your username with quotes.
Great Script, thanks Martin. Plz assist me in getting output in the below format. since i have more than 10000 accounts and it its very difficult to get 25 to 50 rows for each user. Will be possible to separate groups by ;
User1 group1;group2;group3
user2 group2,group3,group7
Manjunath, this seems like a completely different problem. Can’t you just
Get-ADUser $User -Properties MemberOf | Select SamAccountName,MemberOf
?
This is perfect Martin, thank you. The only modification I need is to be able to filter for a specific group/groups with name like “name -like “share*”‘. Any Idea how to edit your original script to return groups that start with “share”?
Thank you in advance for any information you might provide.
Thank you,
Jeff, pipe the function into Where and filter on the Group field
Ok, so I should have stated that I am “self taught” (code for dummy) when it comes to PS. I am struggling with translating what you have suggested into your script? Also, true to my form, I should have thought this through better before I asked on the first go. There are a couple of things that I would like this to do for me. One, filter on the group name, add the employee number to the output, and export to a csv. Can you give me examples on where/how the code might be imputed? Again, thank you for any info you might provide, the script in its original form is still worlds better than what I was dealing with last week…
[…] Get a User’s Group Memberships « The Surly Admin – Get a User’s Group Memberships. Simple script came across this week at Spiceworks. The funny thing was, the script didn’t solve the OP’s problem in the slightest! […]
Pingback by Adgroupmember | Home | January 15, 2016 |
Get-ADUser -Filter {displayname -like “*terminated*”} -ResultSetSize $null | .\Get-UserGroupMembership.ps1 | Export-Csv -NoTypeInformation UserGroupMembership.csv.
above commands gives error when the group is located in diff domain. Is there any way to search GC
Hi Martin,
I’m new to Powershell, completely….My boss has asked me to get a list of active users within a particular OU, then to get the Group members of each user in that list – I’ve managed to find and use a script to get a csv of all enabled user’s in that OU….how do I use that CSV file to get all group memberships for each user in that list? I’m stumped completely!!!
For reference I used:
Get-ADUser -SearchBase ‘OU=XXXX,OU=XXXX,DC=XXXX,DC=Local’ -filter {enabled -eq “True”} | Select-Object SamAccountName,Name,Surname | Format-Table | Out-file -file “C:\AD – Query Reports\Active Users.CSV”
this has got me the csv of active users as required, but no idea how interrogate sourcing this file to find each entry’s group membership?
Appreciate any help you can give !!
Great blog, many thanks
Nice script thanks. What if want to see all groups that the user is also a indirect member of? Right now the script is only showing direct group membership, but it would be quite useful to see all other groups that might be coming from group nesting.
I don’t follow. User is a member of a group or they aren’t.
A user can be a member of let’s say “Sales Global” but then “Sales Global” can be a member of “Sales NA” and “Sales EU” which makes the user a indirect member of those groups as well. For example if you run a “gpresult /r /scope user” on users context you will see all the group memberships including indirect.
They wouldn’t be an inderect member, they are just a member of those other groups. It doesn’t matter if it is through the use of a nested group or their specific user account.
This script will pull ALL of the users group memberships.
Are you asking if it can define when that membership is provided through a nested group?
Regards,
Brian
When I run the script against my own admin account in our domain I only see the groups (33 of them) which I can also see under “Member of” tab in ADUC. I do not see any groups that I am an indirect member of trough nested groups. When I run “gpresult /r /scope user” when logged on with that account it gives me the all my security group memberships (which is 817 of them). Am I missing something here when I run the script? I’m using the basic syntax “PS C:\>.\Get-UserGroupMembership.ps1 -User myadminaccount”
No, not missing anything the script just wasn’t designed to look for that. You’d have to look at the “MemberOf” property on all of the groups you are a member of and work your way up. And then what about double nested groups? So then you’d have to check the “MemberOf’ of the next level up and recurse your way until you hit the top.
OK, thanks for the clarification.
My one liner to extract user memberof group do the job quickly
(Get-ADuser -Filter {name -like “*”})|%{$u=(Get-ADPrincipalGroupMembership $_).name -join “,”; $_.name,$_.givenname,$_.surname,$_.enabled,$u -join “,”}
https://gallery.technet.microsoft.com/scriptcenter/Powershell-One-Liner-Easy-74f976e5
Regards
I’ve been user your Get-UserGroupMembership.ps1 script and I’m having issues with intra-forest output. It will not return anything outside the current domain. Any tips tricks to use?
[…] originally looking for this solution, I ran across the following link if you want to refer to that […]
Pingback by How to get a list of groups for user - Andy's Blog | August 7, 2017 |