Quick Tip: Using PowerShell with Active Directory to Find Groups and Users

using powershell with active directoryA colleague recently faced an issue where he needed to get a list of users out of Active Directory that were part of a specific type of group.

For Windows Server 2008 R2 and Above

You can use these simple scripts to call up your list of users in groups:

Get-ADGroup -filter {GroupScope -eq “DomainLocal”}
Get-ADGroup -filter {GroupScope -eq “Global”}
Get-ADGroup -filter {GroupScope -eq “Universal”}

For Windows Server 2008 and Below

In this case, what my colleague needed was Universal groups, but any other group types can be substituted in this PowerShell example. Below is an easy way to pull this information by using PowerShell with Active Directory.

The GroupType attribute in Active Directory is not stored as a string. If you query the GroupType of a group, it won’t come back as Security or Universal. The GroupType attribute in AD is a number, such as:

 

Value

GroupType

2 Global distribution group
4 Domain local distribution group
8 Universal distribution group
-2147483646 Global security group
-2147483644 Domain local security group
-2147483640 Universal security group

The following script searches Active Directory for Universal groups and, per group, lists members of the group:

Import-Module ActiveDirectory
$groups = Get-ADGroup -Filter * -Properties GroupType | where {$_.GroupType -eq “-2147483640”}
foreach($group in $groups){
Get-ADGroupMember -Identity $group.Name | Select @{Expression={$group.Name};Label=”GroupName”},Name | Export-CSV C:\GroupMembers.csv -NoTypeInformation -Append
}

Let’s go line by line and look at what exactly we’re doing:

$groups = Get-ADGroup -Filter * -Properties GroupType | where {$_.GroupType -eq “-2147483640”}

This is querying all of your Active Directory groups that are Universal groups and then storing them in the $groups variable.

foreach($group in $groups){

For each of the groups in the $groups variable, do the following:

Get-ADGroupMember -Identity $group.Name | Select @{Expression={$group.Name};Label=”GroupName”},Name | Export-CSV C:\GroupMembers.csv -NoTypeInformation -Append

}

Get the Active Directory members of a group and then write the Group Name and User Name to “C:\GroupMembers.csv”.

The resulting .csv file will look something like this:

“GroupName”,”Name”
“All Employees”,”Jane Doe”
“All Employees”,”George Doe”
“All Employees”,”Nancy Doe”
“All Employees”,”Trevor Doe”
“Accounting”,”Trevor Doe”
“Accounting”,”Ted Doe”
“Accounting”,”Nancy Doe”
“Accounting”,”Jane Doe”

This is a simple, great method to easily understand what users are in what groups.

If you have questions about your Active Directory, email us or give us a call at 502-240-0404 and we can help!