Powershell function for gathering users in groups

A friend of mine asked me a couple of days ago if I knew a way to gather users who are members of given groups. I thought to myself “Hmm, challenge accepted!” and started writing a small powershell script.

After he confirmed that the script worked as planned I decided to make a function of it (Yes, I know it has been a lot of them on this blog lately).
The function accepts two parameters: GroupNames and Filelocation. In addition there is an optional switch called KeepCSV.
Rest of the function isn’t that interesting, if you want to use it you can always consult the help (get-help get-membersinadgroups) that I actually have created Smilie: :)

Heres the code:

function Get-MembersInADGroups
 Get-ADGroup -LDAPFilter "(name=$GroupNames)" | export-csv $FileLocationtemp.csv -NoTypeInformation

 $groups = Import-Csv $FileLocationtemp.csv

 $groups | ForEach-Object {
 $groupname = $_.SamAccountname
 Get-ADGroupMember -Identity $_.SamAccountName | select-object name,samaccountname | Out-File $Filelocation$groupname.txt -Encoding utf8
 if ($KeepCSV)
    Write-Host "CSV file is now saved as $filelocationtemp.csv"
    Remove-Item $FileLocationtemp.csv
 Gathers members in given group(s) and puts the result in txt files
 This function will gather all users in the group(s) you specify and write a txt file for each group containing the users who are member of that group. The function accepts wildcards in group name
 .Parameter Groupnames
 This parameter defines what group(s) to look for
 .Parameter FileLocation
 This parameter defines where the output files should be saved
 .Parameter KeepCSV
 Defining this switch will not delete the temp.csv file containing the groups which are polled
 Get-MembersInADGroups -GroupNames some_group -Filelocation c:test
 This command will poll Active Directory for the members of some_group and write a file called some_group.txt in c:test
 Get-MembersInADGroups -GroupNames some_group* -Filelocation c:test
 This command will poll Active Directory for members of groups whose name begins with some_group and write a txt file for each of them in c:test

PS: the function requires that you already have loaded the Active Directory module in powershell

Category(s): Active Directory, Microsoft, Powershell
Tags: , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *


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