This blog has moved to http://ThePowerShellGuy.com
Greetings /\/\o\/\/
In this entry I will show how you can use a recursive script to get the all members of a group, including the members that are in nested groups.
Note that the script will not handle groups with more as 1000 (W2K) or 1500 (W2K3) users,
as this is the maximum the Members property will enumerate.
If you have groups that are bigger you need to adapt the script to do a paged search for examples how to do this see :
Large AD queries in Monad The script looks like this :
# Function get-NestedMembers
# List the members of a group including all nested members of subgroups
# /\/\o\/\/ 2006
function get-NestedMembers ($group){
if ($group.objectclass[1] -eq 'group') {
write-verbose "Group $($group.cn)"
$Group.member |% {
$de = new-object directoryservices.directoryentry("LDAP://$_")
if ($de.objectclass[1] -eq 'group') {
get-NestedMembers $de
}
Else {
$de.sAMAccountName
}
}
}
Else {
Throw "$group is not a group"
}
}
Note that I did add the groupname as a Write-Verbose, so it will only show in verbose mode and in verbose mode will only be displayed not passed on to the pipeline , also it will show users that are member of more groups as often as they get found, as show in the examples below you can use group or sort -unique to get a list of them or to only show the users / computers found in more groups once.
# get-NestedMembers usage examples :
# get a group
$group = new-object directoryservices.directoryentry("LDAP://cn=MainGroup,OU=Groups,DC=mow,DC=Local")
# Get all nested members
get-NestedMembers $group
User1
User2
User2
User3
# Show current verbose mode :
MowPS>$VerbosePreference
SilentlyContinue
# Enable Verbose Mode :
$VerbosePreference = 'continue'
get-NestedMembers $group
VERBOSE: Group MainGroup
User1
User2
VERBOSE: Group SubGroup
User2
User3
# Disable Verbose Mode again :
$VerbosePreference = 'SilentlyContinue'
# Group the output to get the doubles
get-NestedMembers $group | group
Count Name Group
----- ---- -----
1 User1 {User1}
2 User2 {User2, User2}
1 User3 {User3}
# Use sort -Unique to get every user only once
get-NestedMembers $group | sort -Unique
User1
User2
User3
Enjoy,
Greetings, /\/\o\/\/
Tags :
Monad msh PowerShell