I discovered something last week – I had not blogged about little things that I thought I had blogged about. What the heck does that mean? It means that I tried to reference my blog for something because I thought “I totally blogged about that”…and found out that was not the case.
Starting now, I am fixing this situation. There was something that popped up today that called for a PowerShell script and the Get-ADGroupMember cmdlet – get a list of users from a list of groups. Some users are in there more than once so this needs to be a distinct list, unless you are into manually cleaning up things like this, and then I will be sad for you. Because that is kinda sad.
I originally wrote a script with two arrays (one for the initial list and one for the de-duped list of users), but even though this is quick and dirty, that was a little too dirty. Enter the Group-Object cmdlet – it takes this list of names and groups them. No black magic this time. Just a cmdlet, that comes baked into PowerShell giving me what I need.
What? You wanted the code too? Oh, OK.
Name: activedirectory get list of users from multiple groups.ps1
Author: Amy Herold
Date: 24 October 2017
Purpose: Get distinct list of users from multiple AD groups.
$groups = @('Admins','Managers','Some Other Group')
$people = New-Object System.Collections.ArrayList;
#--------------get list of users from list of groups--------------
foreach ($g in $groups)
$people.Add(@(Get-ADGroupMember -Identity $g | select name)) | Out-Null;
#------------use group-object and get a distinct list of names--------------
$people.Name | Group-Object | select name
There you have it – quick, dirty and to the point. Enjoy. 🙂
UPDATE: Mathias Jessen tweeted a one liner for this….so no need for the one array! Woohoo!
('Admins','Managers','Some Other Group' |Get-ADGroupMember |Group-Object -Property Name -NoElement).Name
I was trying to do this but was also just trying to get it done, and if in doubt, I slap things in arrays. Thanks Mathias!