Question

Enumerating members of Active Directory Groups

Asked by: Erdrick33

The below script works fine, but I am looking to query the manager of each account queried.  Our AD does hold the manager data in the organization tab, I just don't know the name of the object.  A little help would be appreciated.  Also, I realize my code is sloppy near the end, some pointers on the if then nesting would be nice too, as I couldn't get the if (instr... & instr...) then to work.

Note.  the -vm is so that I don't list voicemail email accounts.

Const EXCHANGE_SERVER_NAME = "ABCXCHSVR"
Const VM = "-VM"
Const ADS_SCOPE_SUBTREE = 2

Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"

Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection

Set objRootDSE = GetObject("LDAP://RootDSE")
objCommand.CommandText = "SELECT sAMAccountName, msExchHomeServerName, homeMDB, " &_
      "department FROM 'LDAP://" & objRootDSE.Get("defaultNamingContext") &_
      "' WHERE objectClass='user' AND objectCategory='person'"
Set objRootDSE = Nothing

objCommand.Properties("Page Size") = 1000
objCommand.Properties("Timeout") = 600
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
objCommand.Properties("Cache Results") = False

Set objRecordSet = objCommand.Execute

Set objFileSystem = CreateObject("Scripting.FileSystemObject")
Set objFile = objFileSystem.OpenTextFile("Users.txt", 2, True, 0)

While Not objRecordSet.EOF
      strServer = "" : strServer = objRecordSet.Fields("msExchHomeServerName")

      If InStr(1, strServer, EXCHANGE_SERVER_NAME, VbTextCompare) > 0 Then
            strUsername = "" : strStore = "" : strDepartment = ""
            strUsername = objRecordSet.Fields("sAMAccountName")
            strStore = objRecordSet.Fields("homeMDB")
            strDepartment = objRecordSet.Fields("department")

            If instr(strServer, 2) = 0 Then
                  If instr(strServer, 3) = 0 &
                        If instr(1, strUsername, VM, VbTextCompare) = 0 Then
                              objFile.WriteLine strUsername & VbTab & strDepartment
                        End If
                  End If
            End If
            
      End If

      objRecordSet.MoveNext
WEnd

Set objFile = Nothing
Set objFileSystem = Nothing
Set objRecordSet = Nothing
Set objCommand = Nothing
Set objConnection = Nothing

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2007-10-19 at 13:44:20ID22905649
Tags

active

,

directory

,

enumerate

Topics

VB Script

,

Windows 2003 Server

,

Exchange Email Server

Participating Experts
4
Points
500
Comments
9

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. const member functions.
    Hello, Why can't const Class Objects call non-const member functions? Thanks Shayad.
  2. CreateObject
    I have a program that uses the createobject for word so that I can use the spell checker my problem is that not all users have word. Is there a way that I can check if the createobject("Word.application") is going to work before I run the command?
  3. enum to Const Char
    enum names { a = 0, b = 1, c = 2 }; cout<<names(a)<<endl; names(a) returns 0 how do I make this 0 into a const char * or RWCString
  4. Asterisk voicemail indication
    Hi, ive just installed Asterisk 1.5 and have connected Cisco Phones to it. All seems fine i can make VoIP calls and PSTN breakout calls etc. The problem i have is the voicemail indicator. When leaving a message on the voicemail of an extension the message indication light tu...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: mdiglioPosted on 2007-10-19 at 13:53:50ID: 20112314

Hello,
The field you are looking for is called manager

"SELECT manager,sAMAccountName, msExchHomeServerName, homeMDB, " &_
      "department FROM 'LDAP://" & objRootDSE.Get("defaultNamingContext") &_
      "' WHERE objectClass='user' AND objectCategory='person'"

 

by: mdiglioPosted on 2007-10-19 at 14:07:20ID: 20112410

When you come across an attribute you would like to know more about or find out how to query it try using adsiedit.
http://www.computerperformance.co.uk/w2k3/utilities/adsi_edit.htm
I can't help you much with the other problem... I can't figure out what you're after

 

by: RobSampsonPosted on 2007-10-19 at 18:22:20ID: 20113419

This may help you, or be a bit different, but it's the same idea:
http://www.experts-exchange.com/OS/Microsoft_Operating_Systems/Q_22786454.html

Regards,

Rob.

 

by: chandru_solPosted on 2007-10-19 at 19:53:36ID: 20113561

If the above your script is outputting the username and the department, then this should work.

You have not queried the manager in the query.

Try this......

Const EXCHANGE_SERVER_NAME = "ABCXCHSVR"
Const VM = "-VM"
Const ADS_SCOPE_SUBTREE = 2

strOU = "India,"

Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"

Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection

Set objRootDSE = GetObject("LDAP://RootDSE")
objCommand.CommandText = "SELECT sAMAccountName, msExchHomeServerName, homeMDB, " &_
      "department, manager FROM 'LDAP://" & strOU & objRootDSE.Get("defaultNamingContext") &_
      "' WHERE objectClass='user' AND objectCategory='person'"
Set objRootDSE = Nothing

objCommand.Properties("Page Size") = 1000
objCommand.Properties("Timeout") = 600
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
objCommand.Properties("Cache Results") = False

Set objRecordSet = objCommand.Execute

Set objFileSystem = CreateObject("Scripting.FileSystemObject")
Set objFile = objFileSystem.OpenTextFile("Users.txt", 2, True, 0)

While Not objRecordSet.EOF
      strServer = "" : strServer = objRecordSet.Fields("msExchHomeServerName")

      If InStr(1, strServer, EXCHANGE_SERVER_NAME, VbTextCompare) > 0 Then
            strUsername = "" : strStore = "" : strDepartment = ""
            strUsername = objRecordSet.Fields("sAMAccountName")
            strStore = objRecordSet.Fields("homeMDB")
            strDepartment = objRecordSet.Fields("department")
            strmanager = objRecordSet.Fields("manager")

            If instr(strServer, 2) = 0 Then
                  If instr(strServer, 3) = 0 &
                        If instr(1, strUsername, VM, VbTextCompare) = 0 Then
                              objFile.WriteLine strUsername & VbTab & strDepartment & VbTab & strmanager
                        End If
                  End If
            End If
           
      End If

      objRecordSet.MoveNext
WEnd

Set objFile = Nothing
Set objFileSystem = Nothing
Set objRecordSet = Nothing
Set objCommand = Nothing

 

by: Chris-DentPosted on 2007-10-20 at 01:23:05ID: 20114136


It's a little incorrect with those InStr's as they are right now. The manager will return as a Distinguished Name, if that's not what you want it can be changed (example below).

I've added some comments which will hopefully make the changes I've made clear.


Const EXCHANGE_SERVER_NAME = "ABCXCHSVR"
Const VM = "-VM"
Const ADS_SCOPE_SUBTREE = 2

' If you're using this in the LDAP Path below you must include OU= or
' it won't work.

strOU = "OU=India,"

Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"

Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection

Set objRootDSE = GetObject("LDAP://RootDSE")
objCommand.CommandText = "SELECT sAMAccountName, msExchHomeServerName, homeMDB, " &_
      "department, manager FROM 'LDAP://" & strOU & objRootDSE.Get("defaultNamingContext") &_
      "' WHERE objectClass='user' AND objectCategory='person'"
Set objRootDSE = Nothing

objCommand.Properties("Page Size") = 1000
objCommand.Properties("Timeout") = 600
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
objCommand.Properties("Cache Results") = False

Set objRecordSet = objCommand.Execute

Set objFileSystem = CreateObject("Scripting.FileSystemObject")
Set objFile = objFileSystem.OpenTextFile("Users.txt", 2, True, 0)

While Not objRecordSet.EOF
      strServer = "" : strServer = objRecordSet.Fields("msExchHomeServerName")

      If InStr(1, strServer, EXCHANGE_SERVER_NAME, VbTextCompare) > 0 Then
            strUsername = "" : strStore = "" : strDepartment = ""
            strUsername = objRecordSet.Fields("sAMAccountName")
            strStore = objRecordSet.Fields("homeMDB")
            strDepartment = objRecordSet.Fields("department")
            strManagerDN = objRecordSet.Fields("manager")

            ' Getting the managers User Name and Display Name

            Set objManager = GetObject("LDAP://" & strManagerDN)
            strManagerUsername = objManager.Get("sAMAccountName")
            strManagerDisplayName = objManager.Get("displayName")
            Set objManager = Nothing

            ' strManagerUsername and strManagerDisplayName can be used
            ' when generating the output below if required.

            ' Changed 2 to "2" to make it clear it's a string comparison.
            ' If must end with Then before you can use another If. Or the two
            ' can be combined onto one line (this will result in a list of Users where
            ' the Exchange Server Name doesn't include 2 or 3, but does match the
            ' server name at the top

            If instr(strServer, "2") = 0 And If instr(strServer, "3") = 0 Then
                  If instr(1, strUsername, VM, VbTextCompare) = 0 Then
                        objFile.WriteLine strUsername & VbTab & strDepartment & VbTab & strmanager
                  End If
            End If
      End If

      objRecordSet.MoveNext
WEnd

Set objFile = Nothing
Set objFileSystem = Nothing
Set objRecordSet = Nothing
Set objCommand = Nothing

 

by: Erdrick33Posted on 2007-10-22 at 07:24:41ID: 20123357

Chris, I'm wanting to query the entire directory, not just accounts limited to one OU.  Is there a way to utilize this script accross the entire AD?

Also, when I do limit the scope of the search, and specify an OU, I get an error at line 45, char 13, error 0x80005000 code 80005000, source (null).

 

by: Chris-DentPosted on 2007-10-22 at 07:31:32ID: 20123423


Certainly, if you remove "strOU" it will query everything. That makes this section:

objCommand.CommandText = "SELECT sAMAccountName, msExchHomeServerName, homeMDB, " &_
      "department, manager FROM 'LDAP://" & strOU & objRootDSE.Get("defaultNamingContext") &_
      "' WHERE objectClass='user' AND objectCategory='person'"

Into:

objCommand.CommandText = "SELECT sAMAccountName, msExchHomeServerName, homeMDB, " &_
      "department, manager FROM 'LDAP://" & objRootDSE.Get("defaultNamingContext") &_
      "' WHERE objectClass='user' AND objectCategory='person'"

Which will extract all user accounts within the current domain because of the ADS_SCOPE_SUBTREE setting.

The error message you're receiving means it's trying to connect to a Manager for a user that doesn't actually have one. I've put a little in to handle those situations as well as including the change above in the script below.


Const EXCHANGE_SERVER_NAME = "ABCXCHSVR"
Const VM = "-VM"
Const ADS_SCOPE_SUBTREE = 2

Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"

Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection

Set objRootDSE = GetObject("LDAP://RootDSE")
objCommand.CommandText = "SELECT sAMAccountName, msExchHomeServerName, homeMDB, " &_
      "department, manager FROM 'LDAP://" & objRootDSE.Get("defaultNamingContext") &_
      "' WHERE objectClass='user' AND objectCategory='person'"
Set objRootDSE = Nothing

objCommand.Properties("Page Size") = 1000
objCommand.Properties("Timeout") = 600
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
objCommand.Properties("Cache Results") = False

Set objRecordSet = objCommand.Execute

Set objFileSystem = CreateObject("Scripting.FileSystemObject")
Set objFile = objFileSystem.OpenTextFile("Users.txt", 2, True, 0)

While Not objRecordSet.EOF
      strServer = "" : strServer = objRecordSet.Fields("msExchHomeServerName")

      If InStr(1, strServer, EXCHANGE_SERVER_NAME, VbTextCompare) > 0 Then
            On Error Resume Next
            strUsername = "" : strStore = "" : strDepartment = "" : strManagerDN = ""
            strUsername = objRecordSet.Fields("sAMAccountName")
            strStore = objRecordSet.Fields("homeMDB")
            strDepartment = objRecordSet.Fields("department")
            strManagerDN = objRecordSet.Fields("manager")
            On Error Goto 0

            ' Getting the managers User Name and Display Name

            If Not IsNull(objRecordSet.Fields("manager")) Then
                  Set objManager = GetObject("LDAP://" & strManagerDN)
                  strManagerUsername = objManager.Get("sAMAccountName")
                  strManagerDisplayName = objManager.Get("displayName")
                  Set objManager = Nothing
            End If

            ' strManagerUsername and strManagerDisplayName can be used
            ' when generating the output below if required.

            ' Changed 2 to "2" to make it clear it's a string comparison.
            ' If must end with Then before you can use another If. Or the two
            ' can be combined onto one line (this will result in a list of Users where
            ' the Exchange Server Name doesn't include 2 or 3, but does match the
            ' server name at the top

            If instr(strServer, "2") = 0 And If instr(strServer, "3") = 0 Then
                  If instr(1, strUsername, VM, VbTextCompare) = 0 Then
                        objFile.WriteLine strUsername & VbTab & strDepartment & VbTab & strmanager
                  End If
            End If
      End If

      objRecordSet.MoveNext
WEnd

Set objFile = Nothing
Set objFileSystem = Nothing
Set objRecordSet = Nothing
Set objCommand = Nothing

 

by: Erdrick33Posted on 2007-10-22 at 07:40:37ID: 20123503

Chris, once again, you are amazing.

I don't want to take too much more of your time, but I was hoping you could give me a walkthrough of the error checkign you wrote.  I never really have written error checking into my code.
Also, if it errors, will it still display the user with the information other than manager, or nothign at all?

Thank so much Chris.

 

by: Chris-DentPosted on 2007-10-22 at 08:26:07ID: 20123894


These lines are perhaps the most useful to read in terms of error control:

            On Error Resume Next
            ...
            On Error Goto 0

The "On Error Resume Next" statement turns on error handling in VbScript, it'll continue running the script if it bumps into errors. "On Error Goto 0" turns that behaviour back off again, if it bumps into a problem after that the script will still end with an error message.

That's the first part, it allows us to catch error messages and deal with them instead of having to prevent every single one.

Because we're skipping errors this kind can be quite important:

            strUsername = "" : strStore = "" : strDepartment = "" : strManagerDN = ""

It sets each of the variables we're looking at to "" (an empty string), it makes sure we don't carry over any information from the last user we looked at in the Record Set. The Colon (:) tells VbScript to treat it as a line break. There's no difference between the code above and this:

            strUsername = ""
            strStore = ""
            strDepartment = ""
            strManagerDN = ""

Once we've made sure they're empty we can attempt to load values into each:

            strUsername = objRecordSet.Fields("sAMAccountName")
            strStore = objRecordSet.Fields("homeMDB")
            strDepartment = objRecordSet.Fields("department")
            strManagerDN = objRecordSet.Fields("manager")

That saves us having to check each value individual for Null.

This next section isn't so good at the moment (as it was only in as a demonstration):

            If Not IsNull(objRecordSet.Fields("manager")) Then
                  ...
            End If

We check that Manager has something in it (the value is not null), which is good. But we don't clear out the old values, meaning that if we use those without further checks we'll end up with the values from the last successful user. Changing it to this would make sure we don't carry anything over:

            strManagerUsername = "" : strManagerDisplayName = ""
            If Not IsNull(objRecordSet.Fields("manager")) Then
                  Set objManager = GetObject("LDAP://" & strManagerDN)
                  strManagerUsername = objManager.Get("sAMAccountName")
                  strManagerDisplayName = objManager.Get("displayName")
                  Set objManager = Nothing
            End If

Then each of those can be included when we write the line to the file as follows:

                  If instr(1, strUsername, VM, VbTextCompare) = 0 Then
                        objFile.WriteLine strUsername & VbTab & strDepartment & VbTab &_
                                    strManagerUsername & VbTab & strManagerDisplayName
                  End If

Chris

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...