Powershell: A script to find all members of several groups refined

One of the scripts that I use most often is the one I wrote about back in September of 2019. Usually, I only run it for up to ten or so groups, so it’s not a big problem to simply swap out the group name, rince and repeat. Recently, however, I needed to run it for more than five hundred groups. The sheer amount of data makes that a very different proposition.

Luckily, I had recently also written about needing to add a user to a large number of groups. My reasoning was that, if I were to combine the two scripts, maybe I might be able to more or less automate the entire process? As part of the process, I added some more code to highlight what was the group name, and where one saw the group members, essentially making the output a little more human friendly.

I first created the list of groups, the same way I did last week. I then changed up the ForEach-loop from my original script to use the groups, and added comments (which start with a #) to ensure that it is easier to understand. I also added some extraneous bits, calling out (in the final document) which group contains which users. The final script looks as follows:

$Groups = @("Group001";
"GroupN";) #specifies what groups to use in the ForEach loop
ForEach ($Group in $Groups){
"Group Name:" | Out-File -FilePath .\Groupmembers.txt -append
Get-ADGroup $Group -property SamAccountName | select SamAccountName | Out-File -FilePath .\Groupmembers.txt -append #appends the name of the group being queried
"--- --- --- ---" | Out-File -FilePath .\Groupmembers.txt -append
"Group Members:" | Out-File -FilePath .\Groupmembers.txt -append
Get-ADGroupMember $Group -recursive | Get-ADUser -property Displayname | select Displayname | Out-File -FilePath .\Groupmembers.txt -append #appends the result of this query, adding the group members (recursive; gets all individual members in the hierarchy of groups)
"--- --- --- ---" | Out-File -FilePath .\Groupmembers.txt -append

Using this script, what would otherwise have been a very tedious and time consuming task was completed with relative ease, within just a few minutes.



, ,



By posting a comment, you consent to our collecting the information you enter. See privacy policy for more information.

This site uses Akismet to reduce spam. Learn how your comment data is processed.