Solved

Query OU in Active Directory and Return a Member List

Posted on 2008-10-28
17
5,829 Views
Last Modified: 2013-12-24
Hi,
 
I'm working on a script that will list the members of an OU and a group and then print the common members to a file. I have the group query working, but the OU query is where my problem lies. In order to break the problem down I've written the OU code as a seperate script. Depending on how I've written the query I've gotten the following errors:

Null: Exception occurred
Table doesn't exist

Provider: One or more error occurred during the processing of command.
I THINK my problem lies with the fact that I need to search on the uniquely named OU such as IT Department, and then have it drill down one step further to get to the non-unique OU Users below it. The group search was easy because they're all unique names.

To illustrate:

Domain--Departments OU---IT Dept OU--Programmers OU--Listed under here are: Computers OU and Users OU  

In summation:

What would be the query to list the members of the non-uniquely named "Users OU" under Programmers since a Users OU exists at the bottom of every dept OU? Is there some way that I can list the OU as Programmers\Users or ????

I've enclosed the group list code that works. I ASSUME that I should be doing something very similar for the OU portion.

Thanks in advance,

JB
strGroup = InputBox("Please put the desired group name:","Group name") 
 

strFileName = "c:\members_of_" & strGroup & ".txt" 
 

Set objFSO = CreateObject("Scripting.FileSystemObject") 

Set objOutputFile = objFSO.OpenTextFile(strFileName, 2, true, 0) 
 

objOutputFile.WriteLine "Members of group " & strGroup 

objOutputFile.WriteLine "-----------------------------------" 
 

Set oConnection = CreateObject("ADODB.Connection") 

Set oCommand = CreateObject("ADODB.Command") 

oConnection.Provider = "ADsDSOObject" 

oConnection.Open "Active Directory Provider" 

Set oCommand.ActiveConnection = oConnection 
 

sQuery = "SELECT cn, distinguishedName From 'LDAP://dc=xxxx,dc=xx,dc=xxxxx,dc=xxx' where cn='" & strGroup & "'" 
 

oCommand.CommandText = sQuery 

Set oResults = oCommand.Execute 
 
 

On Error Resume Next 
 
 

Set objGroup = GetObject _ 

  ("LDAP://" & oResults.Fields("distinguishedName")) 

objGroup.GetInfo 
 
 

arrMemberOf = objGroup.GetEx("member") 
 
 

For Each strMember in arrMemberOf 
 
 

'this portion will only write the cn of the user or group 

' 

       strlength = InStr(strMember,",") - Instr(strMember,"CN=") 

       msgStart = Instr(strMember,"CN=") 

       msgValue = Mid(strMember,msgStart,strlength) 

       

      ' WScript.echo Right(msgValue, Len(msgValue)-3) 

       objOutputFile.WriteLine Right(msgValue, Len(msgValue)-3) 
 

'WScript.Echo strMember
 

'This portion writes the whole dn-string 

' 

        'objOutputFile.WriteLine strMember 
 
 

Next 
 

WScript.Echo ("Log created and updated. ") & strFileName 
 

'End of script -----------------

Open in new window

0
Comment
Question by:JB4375
  • 8
  • 4
  • 3
  • +2
17 Comments
 
LVL 31

Expert Comment

by:Henrik Johansson
ID: 22824561
The LDAP-path is in the format LDAP://OU=Bottom,OU=Path,OU=Parent,DC=domain,DC=com

You nead to fetch the OU as a recordset and loop through the recordset.


rsOU.Open("<LDAP://OU=Bottom,OU=Path,OU=Parent,DC=domain,DC=com>;(objectCategory=Group);AdsPath;subtree")

Do While Not rsOU.EOF

  Set objGroup=GetObject(rsOU.adsPath)

  ...

  rsOU.moveNext

Loop

Open in new window

0
 
LVL 76

Expert Comment

by:David Lee
ID: 22824633
Hi, JB4375.

To get an OU sQuery needs to be something like this

"SELECT ADsPath,mail,samAccountName FROM 'LDAP://servername.company.com/ou=MySubOU,ou=MyMainOU,dc=company,dc=com' WHERE objectClass='user' AND objectCategory='Person'"
0
 
LVL 9

Assisted Solution

by:gregcmcse
gregcmcse earned 100 total points
ID: 22824638
Here's a somewhat basic way to do what you want.  If the OU is at all large, you'll want to use ADODB, rather than the GetObject method.

Set oConn = CreateObject("ADODB.Connection")

oConn.Provider = "ADsDSOOBJECT"

oConn.Open "ADs Provider"

Set oComm = CreateObject("ADODB.Command")

oComm.ActiveConnection = oConn
 

strServer = "OneOfMyDCs"	' You technically don't need to specify the DC, but it can be much faster if you do

FQDN = "'dc=xxxx,dc=xx,dc=xxxxx,dc=xxx"
 

strCmd = "<LDAP://" & strServer & "/" & FQDN & ">;(&(objectclass=user)(objectcategory=person));cn,distinguishedName,userPrincipalName;subtree"

oComm.CommandText = strCmd
 

Set oRS = oComm.Execute
 

Do Until oRS.EOF

	strUser = oRS.Fields("cn")	' CN=Administrator

	objOutputFile.WriteLine "CN: " & strUser
 

	strUserDN = oRS.Fields("distinguishedName")	' CN=Administrator,CN=Users,CN=MyChildDomain,CN=MyDomain,CN=com

	objOutputFile.WriteLine "distinguishedName " & strUserDN
 

	strUserPN = oRS.Fields("userPrincipalName") ' administrator@mychilddomain.mydomain.com

	objOutputFile.WriteLine "userPrincipalName " & strUserPN
 

	oRS.MoveNext

Loop
 

Set oRS = Nothing

Set oComm = Nothing

Set oConn = Nothing

Open in new window

0
 
LVL 1

Author Comment

by:JB4375
ID: 22824918
OK... Never let it be said that Expert Exchange doesn't have people monitoring the queue. This is crazy... 3 responses in like 30 minutes.
@GregMCSE: i tried your script and got the provider: table does not exist. I'm not saying your solution is necessarily incorrect, and in addition I'd be willing to say it's propably my fault, but I digress......
Let's back up: It's a given that whatever OU I want to query I'm actually looking for the members of the OU Users directly beneath it.
When the script runs I want the user prompted for the unique OU name. They enter it, and then they're notified that the txt file is created. I don't want to have to edit the script at the LDAP line every time time a query is to be performed.
Also I'm changing my Intermediate status to Beginner, but only because "Needs Hand Held isn't an option. I'm completely humbled by your expertise. Would it be possible for you to edit the code I've posted when you post the solution?
Thanks again!!
0
 
LVL 9

Expert Comment

by:gregcmcse
ID: 22825510
JB:  I'm assuming you're logged on as an administrator of the domain you are querying...

My code actually had a bug -- there's a single quote inside the FQDN line.
Your FQDN line should probably be like this:
   FQDN = "ou=Users,ou=Programmers,ou=IT Dept,ou=Departments,dc=mydomain,dc=com"

The ";subtree" at the end of line 10 tells it to get users from that level and below.  So if you did...
   FQDN = "ou=IT Dept,ou=Departments,dc=mydomain,dc=com"
...it would get all users in the "IT Dept" OU and below -- which may be useful to you.

The first line in your code sample shows that you know how to build an input box to prompt for the OU... just provide some guidance:
strOU = InputBox("Please enter the OU to query: ","Enter Full OU Path","ou=Users,ou=Programmers,ou=IT Dept,ou=Departments,dc=mydomain,dc=com")

That will pre-populate the answer box with that OU's fully qualified name.
0
 
LVL 1

Author Comment

by:JB4375
ID: 22826411
@GregMCSE:
  1. I've copied the code you provided, and removed the single quote.
  2. I picked an OU at the top of the Active Directory structure, and listed the full path.
  3. I've type it out exactly as it's written to avoid in any case sensitive issues.
At line 13:
Set oRS = oComm.Execute
Error: Provider: Table does not exist.
Any suggestions?
Also... is there some sort of debugging method that can tell me where this LDAP query is pointing, since it doesn't appear to pointing where I think it is?
I'm using Primal Script, in case there's some built feature. Also I've done echos etc. on everything I can think of, but once it gets to the query....I'm stuck.
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 22827697
Hey guys,

I hope you don't mind me offering another solution, but try out this HTA.

It should present you with your OU structure in a list box, so you can select an OU, then click Get Members.

Save the code below to a file with a names such as "GetOUMembers.hta".

Regards,

Rob.
<Html>

<Head>

<Title>List OU Members</Title>

 

<HTA:Application

Caption = Yes

Border = Thick

ShowInTaskBar = Yes

SingleInstance = Yes

MaximizeButton = Yes

MinimizeButton = Yes>

 

<script Language = VBScript>
 

	Sub Window_OnLoad

		intWidth = 800

		intHeight = 600

		Me.ResizeTo intWidth, intHeight

		Me.MoveTo ((Screen.Width / 2) - (intWidth / 2)),((Screen.Height / 2) - (intHeight / 2))

		lst_members.Style.Width = 500

    	Set objRootDSE = GetObject("LDAP://RootDSE")

    	strBaseConnString = objRootDSE.Get("defaultNamingContext")

		Set objOULevel = GetObject("LDAP://" & strBaseConnString)

		RecurseOUs objOULevel, 0, strBaseConnString

		Show_Selection

	End Sub
 

	Sub Clear_Members

		For intListProgress = 1 To lst_members.Length

	   		lst_members.Remove 0

	   	Next

	End Sub
 

	Sub RecurseOUs(objOU, intLevel, strBaseConn)

		Dim objOUObject, strConnString, objActiveOption

		For Each objOUObject In objOU

			If UCase(Left(objOUObject.Name, 3)) = "OU=" Then

				strConnString = objOUObject.DistinguishedName

				Set objActiveOption = Document.CreateElement("OPTION")

		    	If intLevel = 0 Then

		    		objActiveOption.Text = Replace(objOUObject.Name, "OU=", "")

		    	Else

		    		objActiveOption.Text = String(intLevel * 4, " ") & "->   " & Replace(objOUObject.Name, "OU=", "")

		    	End If

		    	objActiveOption.Value = strConnString

		    	lst_SiteFilter.Add objActiveOption

				RecurseOUs GetObject("LDAP://" & strConnString), intLevel + 1, strBaseConn

			End If

		Next

	End Sub
 

	Sub Show_Selection

		span_SiteFilter.InnerHTML = lst_SiteFilter.Value

	End Sub
 

	Sub Default_Buttons

		If Window.Event.KeyCode = 13 Then

			btn_run.Click

		End If

	End Sub
 

	Sub Exit_HTA

		Window.Close

	End Sub
 

	Sub Get_Members

		Clear_Members

		strOU = lst_sitefilter.Value

		strLDAPPath = "LDAP://" & strOU

		

		Set objConnection2 = CreateObject("ADODB.Connection")

		Set objCommand2 = CreateObject("ADODB.Command")

		objConnection2.Provider = "ADsDSOObject"

		objConnection2.Open "Active Directory Provider"

		Set objCommand2.ActiveConnection = objConnection2

		

		Set objOU = GetObject(strLDAPPath)

		For Each objObject In objOU

			Set objMember = Document.CreateElement("OPTION")

			objMember.Text = objObject.cn

	        objMember.Value = objObject.cn

			lst_members.Add objMember, 0

		Next

	End Sub

</script>

<body style="background-color:#B0C4DE;" onkeypress='vbs:Default_Buttons'>

	<table height="90%" width= "90%" border="0" align="center">

		<tr>

			<td align="center" colspan="2">

				<h2>List OU Members</h2>

			</td>

		</tr>

		<tr>

			<td>

				<b>Site Filter:</b>

			</td>

			<td>

			    <select size='1' name='lst_SiteFilter'  onChange='vbs:Show_Selection'>

				</select>

			</td>

		</tr>

		<tr>

			<td colspan=2>

				<b>Site Selected:</b>&nbsp&nbsp&nbsp<span id='span_SiteFilter'></span>

			</td>

		</tr>

		<tr>

			<td>

				<b>Members:</b>

			</td>

			<td>

			    <select size='8' name='lst_members'>

				</select>

			</td>

		</tr>

	</table>

	<table width= "90%" border="0" align="center">

		<tr align="center">

			<td>

				<button name="btn_run" id="btn_run" accessKey="G" onclick="vbs:Get_Members"><u>G</u>et Members</button>

			</td>

			<td>

				<button name="btn_exit" id="btn_exit" accessKey="x" onclick="vbs:Exit_HTA">E<u>x</u>it</button>

			</td>

		</tr>

	</table>

</body>

</head>

</html>

Open in new window

0
 
LVL 1

Author Comment

by:JB4375
ID: 22830744
Hi Rob,
When I execute, it's runs for quite a while, and then I get the following error:
"Could not complete the operation due to error 80005000"
Debug shows error at line 47:
RecurseOUs GetObject("LDAP://" & strConnString), intLevel + 1, strBaseConn
Having said that, if I choose to not debug in order to get rid of the error,  the program actually works which leads me to believe that maybe it's timing out due to size of Active Directory? Also, I did some checking and found another discussion where you said that it would require the fully qualified domain name.
Questions:
  1. Do you think this would help if it was edited so FQDN= blahblah.com and then FQDN was in the get object statement?
  2. In previous research I read that a different method would be need to be used other than Get Object if Active Directory is really large. We have about 12,000 employees, do you think this is the case?
  3. Finally, and I really hate to ask this, but I need to be able to select a group as well, compare members of group and OU, and then list common members. This code is fantastic, but I wouldn't begin to know how to edit it to get what I need.
Thanks,
JB
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 1

Author Comment

by:JB4375
ID: 22835876
OK... I was reading back over this thread. It was actually GregcMCSE that said: If the OU is at all large, you'll want to use ADODB, rather than the GetObject method.
I knew I'd read that somewhere. LOL. Rob, I see you've implemented that. Scratch question 2.
Thanks Guys,
JB


0
 
LVL 9

Assisted Solution

by:gregcmcse
gregcmcse earned 100 total points
ID: 22836006
In a larger Active Directory, and yours does count as one, you can time out queries if you're trying to return too much.

The table error is a very unusual one that is usually related to a typo in the LDAP query line.

Are you sure you're using "DC=" for every domain name portion, "CN=" for any containers (like the built-in "Users" container), and "OU=" for any Organization Units in the structure?

If you're sure you've got it right, are you by any chance running this on a Windows 2000 server with a really old version of MDAC and/or the Windows Scripting Host?  You can go to msdn.microsoft.com and search on "MDAC" and "WSH" to find the latest versions and download them and install them on your workstation and see if you still have the problem after installing those.

I could also see you having issues if you're trying to run this script on Vista.  What is the OS of the machine you're trying to run this on?  You don't have to (and usually shouldn't) run it directly on the domain controller.
0
 
LVL 1

Author Comment

by:JB4375
ID: 22836984
Rob's script appears to query the entire structure for the drop down, and, we have other scripts that do this as well. They're set up for techs to be able to move PC's to different OU's so they don't need to touch AD directly.
I would agree on the table error, LDAP query comment: I've tried this program a few different ways and attempted the LDAP every way I could think of. About all I've accomplished at this point is to learn acceptable syntax.
I know I've got the fully qualified domain right. All the code has been based on an existing scripts that were written by the previous script writer. Like I said the group code I listed at the top works ok
I've actually tried running this from Windows Vista, XP, and Server 2003. I'll check for latest MDAC, and WSH as you suggested.
Side Note: I actually talked with the script requester about these issues. She commented that when she approached the last guy about "whipping this script out" he comment that it was quite a bit more involved than that.
Great! I've written one, and changed a couple of others, nothing like getting the opportunity to ease into it.
Thanks,
JB
0
 
LVL 65

Accepted Solution

by:
RobSampson earned 400 total points
ID: 22837159
Try this...I've added a small bit of error checking around the line you indicated.  This should give a message with the connection string it's trying to use....

My code *does* use the GetObject method to enumerate the OU's in the first place, which could cause issues on a large AD.  If I get time, I'm thinking I could just run an ADODB LDAP query to return all OU's, then build the indented list based on the amount of elements in the OU path......but I'm not sure if that will order out correctly....

Regards,

Rob.
<Html>

<Head>

<Title>List OU Members</Title>

 

<HTA:Application

Caption = Yes

Border = Thick

ShowInTaskBar = Yes

SingleInstance = Yes

MaximizeButton = Yes

MinimizeButton = Yes>

 

<script Language = VBScript>
 

	Sub Window_OnLoad

		intWidth = 800

		intHeight = 600

		Me.ResizeTo intWidth, intHeight

		Me.MoveTo ((Screen.Width / 2) - (intWidth / 2)),((Screen.Height / 2) - (intHeight / 2))

		lst_members.Style.Width = 500

    	Set objRootDSE = GetObject("LDAP://RootDSE")

    	strBaseConnString = objRootDSE.Get("defaultNamingContext")

		Set objOULevel = GetObject("LDAP://" & strBaseConnString)

		RecurseOUs objOULevel, 0, strBaseConnString

		Show_Selection

	End Sub
 

	Sub Clear_Members

		For intListProgress = 1 To lst_members.Length

	   		lst_members.Remove 0

	   	Next

	End Sub
 

	Sub RecurseOUs(objOU, intLevel, strBaseConn)

		Dim objOUObject, strConnString, objActiveOption

		For Each objOUObject In objOU

			If UCase(Left(objOUObject.Name, 3)) = "OU=" Then

				strConnString = objOUObject.DistinguishedName

				Set objActiveOption = Document.CreateElement("OPTION")

		    	If intLevel = 0 Then

		    		objActiveOption.Text = Replace(objOUObject.Name, "OU=", "")

		    	Else

		    		objActiveOption.Text = String(intLevel * 4, " ") & "->   " & Replace(objOUObject.Name, "OU=", "")

		    	End If

		    	objActiveOption.Value = strConnString

		    	lst_SiteFilter.Add objActiveOption

				On Error Resume Next

				RecurseOUs GetObject("LDAP://" & strConnString), intLevel + 1, strBaseConn

				If Err.Number <> 0 Then

					MsgBox "Error enumerating " & strConnString

				End If

				Err.Clear

				On Error GoTo 0

			End If

		Next

	End Sub
 

	Sub Show_Selection

		span_SiteFilter.InnerHTML = lst_SiteFilter.Value

	End Sub
 

	Sub Default_Buttons

		If Window.Event.KeyCode = 13 Then

			btn_run.Click

		End If

	End Sub
 

	Sub Exit_HTA

		Window.Close

	End Sub
 

	Sub Get_Members

		Clear_Members

		strOU = lst_sitefilter.Value

		strLDAPPath = "LDAP://" & strOU

		

		Set objConnection2 = CreateObject("ADODB.Connection")

		Set objCommand2 = CreateObject("ADODB.Command")

		objConnection2.Provider = "ADsDSOObject"

		objConnection2.Open "Active Directory Provider"

		Set objCommand2.ActiveConnection = objConnection2

		

		Set objOU = GetObject(strLDAPPath)

		For Each objObject In objOU

			Set objMember = Document.CreateElement("OPTION")

			objMember.Text = objObject.cn

	        objMember.Value = objObject.cn

			lst_members.Add objMember, 0

		Next

	End Sub

</script>

<body style="background-color:#B0C4DE;" onkeypress='vbs:Default_Buttons'>

	<table height="90%" width= "90%" border="0" align="center">

		<tr>

			<td align="center" colspan="2">

				<h2>List OU Members</h2>

			</td>

		</tr>

		<tr>

			<td>

				<b>Site Filter:</b>

			</td>

			<td>

			    <select size='1' name='lst_SiteFilter'  onChange='vbs:Show_Selection'>

				</select>

			</td>

		</tr>

		<tr>

			<td colspan=2>

				<b>Site Selected:</b>&nbsp&nbsp&nbsp<span id='span_SiteFilter'></span>

			</td>

		</tr>

		<tr>

			<td>

				<b>Members:</b>

			</td>

			<td>

			    <select size='8' name='lst_members'>

				</select>

			</td>

		</tr>

	</table>

	<table width= "90%" border="0" align="center">

		<tr align="center">

			<td>

				<button name="btn_run" id="btn_run" accessKey="G" onclick="vbs:Get_Members"><u>G</u>et Members</button>

			</td>

			<td>

				<button name="btn_exit" id="btn_exit" accessKey="x" onclick="vbs:Exit_HTA">E<u>x</u>it</button>

			</td>

		</tr>

	</table>

</body>

</head>

</html>

Open in new window

0
 
LVL 1

Author Comment

by:JB4375
ID: 22840970
Rob,
I'll check this out, ASAP. We're trying to get all of our servers patched with the latest updates. Just wanted to get on here and give some feedback.
I also want to say that this has been SUCH a good experience interacting with all of you on this problem.  
Thanks again,
JB
 
 
0
 
LVL 1

Author Comment

by:JB4375
ID: 22843352
OK. I've tested it, and it works. It does take about 2 minutes to come up, but once it's there I can do mulitpe queries with it.
It also pointed out a problem OU that it was unable to enumerate. It had a huge name that should have been listed in the description. Once I made the changes in active directory, it shaved about 30 seconds off the load time.
Next question: Getting the group member drop down and listing common members of the group and OU. I need it to work in this manner, and specified it at the top. However, after so much has gone into this, should this be a seperate, related question?
I just want to be fair about point values etc. and since you've all been here longer if it's ok I'll leave it up to you, the experts.
Thanks,
JB
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 22845889
That may be better in a new question, but you would need to explain your requirement a bit better (maybe give an example of outpu), because I can't quite understand what you need.  The Site Filter list box *only* lists OU's, not groups, but the Members list box *does* list groups.  What we might be able to do, is, say you have a group name in the Members box.  We could make it so that when that group name is double-clicked, it's immediate members are shown in a message box, or another list box.....

Regards,

Rob.
0
 
LVL 1

Author Closing Comment

by:JB4375
ID: 31510849
GregcMCSE Provided a solution that I thought was workable, and continued to provide additional information and assistance throughout the thread. Rob Sampson had a more advanced method that was effectively a turn key solution. Both experts, and I mean that very literally, provided an invaluable service.  
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 22846638
Thanks for the grade.

When you post your new question, you can post a link to that here, and we'll check it out.

Regards,

Rob.
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

SQL Command Tool comes with APEX under SQL Workshop. It helps us to make changes on the database directly using a graphical user interface. This helps us writing any SQL/ PLSQL queries and execute it on the database and we can create any database ob…
Synchronize a new Active Directory domain with an existing Office 365 tenant
This tutorial will walk an individual through the process of configuring their Windows Server 2012 domain controller to synchronize its time with a trusted, external resource. Use Google, Bing, or other preferred search engine to locate trusted NTP …
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now