Vbscript to count objects in an OU

KevinO

[H]ard|Gawd
Joined
Aug 6, 2004
Messages
1,433
Anyone know of a way to get a quick count of object in an OU in Active Directory?

Everything I have search for is pretty much:

Code:
Set OU = TestOU

For Each Object in TestOU
    count = count + 1
Next

I don't want to have to do that to get a count of something that can contain 1000+ objects. I was hoping there was a better way or a propert like .count for TestOU.
 
This comes from http://www.experts-exchange.com/Programming/Languages/Visual_Basic/VB_Script/Q_22544394.html

Code:
'Create the OU Recordset
Set adoCmdOU = CreateObject("ADODB.Command")
With adoCmdOU
      .ActiveConnection = adoCon
                'Change YourDomainName on the following line to the name of your domain
      .CommandText = "SELECT adsPath FROM 'LDAP://YourDomainName' Where objectClass='organizationalUnit'"
      .Properties("Size Limit") = 5000
      .Properties("Page Size") = 100
      .Properties("Timeout") = 30
      .Properties("Cache Results") = False
      Set adoRsOU = .Execute()
      Do Until adoRsOU.EOF
            'Get the number of users in the OU
            adoCmdUser.CommandText = "SELECT samAccountName FROM '" & Replace(adoRsOU.fields("ADsPath"), "'", "''") & "' Where objectClass='user' AND objectCategory='Person'"
            Set adoRsUser = adoCmdUser.Execute()
            varTotalUsers = adoRsUser.RecordCount
            'Get the number of mail enabled users in the OU
            adoCmdUser.CommandText = "SELECT samAccountName FROM '" & Replace(adoRsOU.fields("ADsPath"), "'", "''") & "' Where objectClass='user' AND objectCategory='Person' AND mailnickname='*'"
            Set adoRsUser = adoCmdUser.Execute()
            varMailEnabled = adoRsUser.RecordCount
            objFile.WriteLine adoRsOU.Fields("adsPath") & " Total=" & varTotalUsers & " Mail Enabled=" & varMailEnabled
            adoRsOU.MoveNext
      Loop
End With

The short of it is that you need to execute a SQL query, and check the RecordCount:
adoCmdUser.CommandText = "SELECT samAccountName FROM '" & Replace(adoRsOU.fields("ADsPath"), "'", "''") & "' Where objectClass='user' AND objectCategory='Person'"
Set adoRsUser = adoCmdUser.Execute()
varTotalUsers = adoRsUser.RecordCount
 
Back
Top