Wednesday, 16 March 2016

Get all users in AD group using Powershell

We can get a list of members of an AD group using the Powershell cmdlet Get-ADGroupMember. In this post, I am going to write powershell script to list group members in Active Directory group and export group members details to csv file. Before proceed, run the following command to import Active Directory Module.
Import-Module ActiveDirectory
Run the following command to list members of a given AD Group.
Get-ADGroupMember -Identity "<GroupName>" | Select Name, SamAccountName
The below command lists only users from the Domain Admins group.
Get-ADGroupMember -Identity "Domain Admins" | Where-Object {$_.ObjectClass -eq "User"} |
Select Name, SamAccountName

Export AD group members to csv:

The following Powershell command find and gets a list of users of a given AD group and exports member details to CSV file.
$GroupName = "<GroupName>"
Get-ADGroupMember -Identity $GroupName | Where-Object {$_.ObjectClass -eq "User"} | 
Select Name, SamAccountName |
Export-CSV "C:\\ADGroupMembers.csv" -NoTypeInformation -Encoding UTF8

Export group membership of multiple groups:

You can use the below script, if you want to export group membership of multiple groups. First create the text file groups.txt which includes one group name in each line. You will get the group name in first column and group member in second column in the csv file ad-group-members.csv.
$CustomResult=@() 
$groups = Get-Content "C:\\groups.txt"            
$Groups | ForEach-Object {
$group = $_
Get-ADGroupMember $group | ForEach-Object {
$CustomResult += [PSCustomObject] @{ 
                GroupName = $group
                Member = $_.Name
            }           
  }
}
$CustomResult | Export-CSV "C:\\ad-group-members.csv" -NoTypeInformation -Encoding UTF8

Advertisements
Advertisements

No comments:

Post a Comment