Local Tech Repair: Finding all Active Directory groups with over 200 members with Powershell/LDAP

Thursday, May 7, 2015

Finding all Active Directory groups with over 200 members with Powershell/LDAP

Have you ever needed to identify large groups in your organization though do not know how to. Well I was bored and created a script for you so you don't have to worry and can get back to your games... I mean work. 
*edited 5/19/15*
some people noted that instead of using .net to do the ldap query you can do it in the built in modules. this is correct. and for those that are wanting to do that you can do that with the following command. That can run faster. Though I am not sure how it effects the results of numbers if your running a cross forest groups.
get-adgroup -ldapfilter "(&(samaccounttype=268435456)(name=*))" |foreach-object {$counter = get-adgroupmember -identity $_.distinguishedname; if($counter.count -gt 200){$_.distinguishedname}}

*end of edit*

So here is the script.

<# .SYNOPSIS 

finds all distribution groups over 200 members 

.DESCRIPTION 
 Created by Local Tech Repair Admin
 Date: 01/13/2015 
 version: .01 finds all  
 Website: https://localtechrepair.blogspot.com
 finds all distribution groups over 200 members 

.EXAMPLE
 PS C:\Users\username\Desktop\scripts> C:\Users\username\Desktop\scripts\groupsover200.ps1
_ALL Emp  ====> 2550 members
_ALL Emp Non Union ====> 723 members
#>


#starts counter to track how long it took to execute.
$date1 = Get-Date -Date "01/01/1970"
$date2 = Get-Date
$start = (New-TimeSpan -Start $date1 -End $date2).TotalSeconds



#ldap search based off user dns domain name
$root = [ADSI]"LDAP://$env:userdnsdomain"
$search = [adsisearcher]$root
$Search.Filter = "(&(samaccounttype=268435456)(name=*))"
$colResults = $Search.FindAll()

#for each find do another ldap search to count memebers
foreach ($i in $colResults)
{
#gets the distinguished name of the group we are searching for
$distinguishedname = [string]$i.Properties.Item('distinguishedName')

#ldap query pulls the members of the groups distinguishedname
$Search.Filter = "(&(sAMAccountType=805306368)(memberOf:1.2.840.113556.1.4.1941:=$distinguishedname))"
$countresults = $Search.FindAll()
$num = $countresults.count #the actual counting of members.
#checks if there are over 200 members in the group.
if ($num -gt 200){
#writes out the group name and how many members in a single line.
Write-host $i.Properties.Item('Name')" ====> "$num" members"
}
}

#ends counter
$date1 = Get-Date -Date "01/01/1970"
$date2 = Get-Date
$end = (New-TimeSpan -Start $date1 -End $date2).TotalSeconds
$completed = $end - $start
#outputs how long the query took to execute.
Write-Output "Done in seconds" $completed


hope that this helps and don't forget to share it with others so they can play more games... I mean get more work done. 


Thanks for reading, 
Local Tech Repair Admin

No comments:

Post a Comment