How to filter out sub groups in DSQUERY?

1k views Asked by At

In DSQUERY when finding AD objects, I want to find a DL (distribution list) or AD security group, and find all it's users (even in sub groups) and then filter out the sub groups. I have this so far

dsquery group -samid YourGroupName | dsget group -members -expand

from here https://michlstechblog.info/blog/windows-get-all-groups-a-user-is-memberof-by-dsquerydsget-recursive/

but it includes the sub groups. Is there a way I can filter it so that only the users remain? This dsquery does something like that, but I don't know how to tie it in with the above query.

 | dsquery * -filter "(&(objectcategory=person)(objectclass=user))"

Thanks

EDIT:

Lets say I have a group YourGroupName, which has subgroups YourGroupNameA, YourGroupNameB. Then those subgroups have some users User1 (YourGroupNameA group), User2 (YourGroupNameB group), User3 (YourGroupNameB group).

The first query above gets me

YourGroupNameA
YourGroupNameB
User1
User2
User2

However I want to get it like this

User1
User2
User2
1

There are 1 answers

6
Gabriel Luci On BEST ANSWER

If you install RSAT, you can use the AD PowerShell cmdlets. To get the names of each member, recusively, you can use Get-ADGroupMember with its -Recursive parameter:

Get-ADGroupMember YourGroupName -Recursive | Select Name

That will not include the names of the nested groups.

To search by the group name rather than sAMAccountName, you can use Get-ADGroup and pipe it into Get-ADGroupMember:

Get-ADGroup -Filter "Name -eq 'YourGroupName'" |
    Get-ADGroupMember -Recursive |
    Select -Expand Name

If you prefer to use LDAP filters (which is what it gets converted to in the background anyway), you can use the -LDAPFilter parameter:

Get-ADGroup -LDAPFilter "(name=YourGroupName)" |
    Get-ADGroupMember -Recursive |
    Select -Expand Name

If you need to search by the display name (what gets shown in Outlook, for example), then you can replace name with displayName. They're often the same value, but they can be different.

To present it as a JSON string, use ConvertTo-Json:

Get-ADGroup -Filter "Name -eq 'YourGroupName'" |
    Get-ADGroupMember -Recursive |
    Select -Expand Name |
    ConvertTo-Json