Powershell Crushes VBScript with AD query again
In my on going battle on EE to prove the value of powershell, I have destroyed yet another vbscript. While the vbscript look was impressive it was a monsterous 38 lines compaired to Powershell 12. Again with no short-cuts, you could trim another 4 lines with ease.
Here is my code. It gets all the groups and list the group name / member count / OU.
$root = [ADSI]""
$dsSearcher = new-Object System.DirectoryServices.DirectorySearcher($root,$filter)
$dsSearcher.PageSize = 1000
$groups = $dsSearcher.findAll()
@(foreach($group in $groups)
{
[string]$name = $group.Properties.cn
[string]$count = ($group.psbase.properties.member).count
[string]$OU = ((($group.GetDirectoryEntry()).psbase).parent).distinguishedName
"GROUP:{0} Count:{1} OU:{2}" -f $name.PadRight(35),$count.padright(5),$ou
}) | out-file C:\temp\yourfile.txt -enc ASCII
Output looks like this
GROUP:TGroup1 Count: OU:OU=MyGroups,DC=corp,DC=bb,DC=lab
GROUP:TGroup2 Count: OU:OU=MyGroups,DC=corp,DC=bb,DC=lab
GROUP:TGroup3 Count: OU:OU=MyGroups,DC=corp,DC=bb,DC=lab
GROUP:TGroup4 Count:1 OU:OU=MyGroups,DC=corp,DC=bb,DC=lab
GROUP:TGroup5 Count:2 OU:OU=MyGroups,DC=corp,DC=bb,DC=lab
….
tshell :: Aug.31.2007 :: Active Directory, Powershell, Scripting :: No Comments »

With AD cmdlets you could be fine with even less:
Get-QADGroup | ForEach-Object {
[string]$name = $_.Name
[string]$count = (Get-QADGroupMember $_).length
[string]$OU = $_.ParentContainer
“GROUP:{0} Count:{1} OU:{2}” -f $name.PadRight(35),$count.padright(5),$ou
} | out-file C:\temp\yourfile.txt
In general, PowerShell is great for statistics collection. For example, see http://dmitrysotnikov.wordpress.com/2007/04/04/ad-cmdlets-and-domain-statistics/
or
http://dmitrysotnikov.wordpress.com/2007/04/07/domain-statistics-with-powershell-continued/
Nice script as always. One note, computer based groups don’t seem to return an accurate count. At least, not the built-in or well-known groups. When I ran this script it showed zero members of the Domain Controllers group and 39 members of the Domain Computers group when there were actually 7 and 582 respectively. I wonder what causes the discrepency?
This is because Domain Users is the default Primary Group for a user. Default Primary Group for Computer is Domain Computers, and Primary Group for DC\’s in Domain Controllers group. If the primary group membership is changed then backlinks are created.
Basically by default it will appear that Domain Users/Computers/Controllers will look like they have no members via Script.