windowspowershellactive-directory

Checks which AD Groups are empty


Hi guys so i am trying to pull Empty AD groups, it does pull some AD groups but it also pulls groups that do have members, like Domain Users and Domain Computers. This is the script i have

Get-ADGroup -Filter * -Properties Members | where {-not $_.members} 

The script is suppose to return only empty AD groups.


Solution

  • Two things:

    First, as you have it, your query is getting every group on your domain, then the filtering is done on your computer. It would run a lot quicker if you put the filter in Get-ADGroup, like this:

    Get-ADGroup -LDAPFilter "(!member=*)"
    

    (I like to use -LDAPFilter rather than -Filter since it has to translate whatever you put in -Filter into an proper LDAP query anyway. I like having control over the exact query that gets sent.)

    Second, the reason those groups are being returned is because they're being used as a primary group. A user (or computer) is not stored in the member attribute of its primary group. Instead, the primaryGroupId attribute of the user (or computer) is set to the primaryGroupToken of the group. Unfortunately, that makes it difficult to filter those groups out without doing a second search (for each group returned) checking if it is used as a primary group.

    If your organization doesn't ever change the primary group, then it will always be Domain Users for users and Domain Computers for computers, and you can just exclude those groups from your results.