Techibee.com

PowerShell: How to get nested Active Directory group members

This post helps you to understand how to query nested group members using powershell. The MS given ActiveDirectory powershell module doesn’t provide a direct way to get all the members part of a security group. This information is useful because you can know who all will get permissions granted to a particular security group if the security group has sub groups inside it. If there is just one or two levels of sub groups, then maybe we can spend time and write code for querying those groups as well by parsing their names. But how we can handle the situation where we don’t know how many sub groups the group we are querying has and how many levels are there?

To address this requirement I have written a small powershell function that helps you to get all direct and indirect members of a security group in active directory.

function Get-ADNestedGroupMembers {
[cmdletbinding()]
param (
[String] $GroupName
)            

import-module activedirectory
$Members = Get-ADGroupMember -Identity $GroupName
$members | % {
    if($_.ObjectClass -eq "group") {
        Get-ADNestedGroupMembers -GroupName $_.distinguishedName
    } else {
        return $_.distinguishedname
    }
}            

}

In this code I am using Get-ADGroupMember cmdlet which is part of activedirectory module. This code uses recursive function call to query group members when a sub group is found.

Usage:

Hope this helps… please feel free to post in comments section if you have any questions. This script can be enhanced to display objects of a particular type — for example, only computers, only users etc. I am doing it here …but let me know if you have the requirement, I will add the code for that as well.

You can export the output to a file using below command.

Get-ADNestedGroupMembers -GroupName "Test1" | out-file -Filepath c:\temp\test1.txt

 

Hope this helps…

Exit mobile version