UPDATED: PowerShell – WE HAZ YUR ACTIVE DIRECTORY RIGHT HERE!

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.

PowerShell

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

<#

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-ObjectSystem.Collections.ArrayList;

$people.Clear();

#--------------get list of users from list of groups--------------

foreach($gin$groups)

{

$people.Add(@(Get-ADGroupMember-Identity$g|selectname))|Out-Null;

}

#------------use group-object and get a distinct list of names--------------

$people.Name|Group-Object|selectname

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!

PowerShell

1

('Admins','Managers','Some Other Group'|Get-ADGroupMember|Group-Object-PropertyName-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!