PowerShell: Building a script to find all members of several given groups

Last week, I showed you how I find all the nested members of a specified group. When we get requests for such audits, however, they usually specify doing so for a number of groups. Now, we could of course do it, one group at a time, adding information to our output as we go, however the script as written overwrites the file. What, then, if we want to run this on a number of groups, and avoid overwriting the file? That requires the -Append parameter:

Get-ADGroupMember "GROUPNAME" -recursive | Get-ADUser -property Displayname | select Displayname | Out-File -FilePath .\PathOfFileHere.txt -append

This will get messy, and quickly. That is why I like to add another line so that I add the name of the group to the file before listing its members. To do this, I start by using the Get-ADGroup command, sending the output to the file, like so:

Get-ADGroup "GROUPNAME" | Out-File -FilePath .\PathOfFileHere.txt -append

Like last time, however, this outputs far too much information:

DistinguishedName : CN=Administrators,CN=Builtin,DC=Fabrikam,DC=com GroupCategory : Security Group
Scope : DomainLocal
Name : Administrators
ObjectClass : group
ObjectGUID : 02ce3874-dd86-41ba-bddc-013f34019978
SamAccountName : Administrators
SID : S-1-5-32-544

Example result from the Get-ADGroup PowerShell documentation

Since we only want to append the name of the group, that is a bit much. Luckily, we can repurpose the commands we ran when getting the group members. Swapping DisplayName for SamAccountName, the command looks like this:

Get-ADGroup "GROUPNAME" -property SamAccountName | select SamAccountName | Out-File -FilePath .\PathOfFileHere.txt -append

This will output as follows:

SamAccountName
———–
Administrators

Based on the above example result

Combining the two, the complete script – for a single group – looks like this:

Get-ADGroup "GROUPNAME" -property SamAccountName | select SamAccountName | Out-File -FilePath .\PathOfFileHere.txt -append

Get-ADGroupMember "GROUPNAME" -recursive | Get-ADUser -property Displayname | select Displayname | Out-File -FilePath .\PathOfFileHere.txt -append

The output looks like this:

SamAccountName
———–
Administrators

DisplayName
———–
Administrator
Sagiv Hadaya

Based on the above example, as well as on the example from last week’s post.

Depending on who the audience is, you might get away with handing it over like that. If not, removing the extraneous information should be a quick enough job that you can do it using search and replace in notepad.


Posted

in

,

by

Comments

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.