Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

HTA Script to validate the user account in AD

Posted on 2011-02-22
9
Medium Priority
?
1,367 Views
Last Modified: 2012-05-11
Hi All,

I am not much familiar with programing, but I am looking for a Script (preferabbly HTA) that will read the login ID from txt file and validate the list in AD and return the results in either CSV or Excel.

Can anyone please help me with this.

Praveen
0
Comment
Question by:praveendusi
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
9 Comments
 

Author Comment

by:praveendusi
ID: 34985519
Team,

I know that this is a simple question.  But need your help.

Praveen
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 34991105
Why would this need to be a HTA if you're outputting the data to CSV anyway?  Would a VBS do that takes the inputfile and checks that each samAccountName is in AD?

Regards,

Rob.
0
 

Author Comment

by:praveendusi
ID: 34994589
Hi Rob,

Thank you for the response.  

The reason I wanted HTA is because this would be given to my team.  Some are not very familiar with VBScript.  I can understand the VB script but cannot change it as I am still learning.... :))

HTA would be good.... If that cannot be done... VB file is OK with Input boxes.

My requirement:

1)  Script should read the txt file which contains the Login Accounts (UserID)
2)  It should output if the account exits or not.  If exists, full path of the OU.

Let me know if you need any more information.

Many Thanks
Praveen
0
Get your Disaster Recovery as a Service basics

Disaster Recovery as a Service is one go-to solution that revolutionizes DR planning. Implementing DRaaS could be an efficient process, easily accessible to non-DR experts. Learn about monitoring, testing, executing failovers and failbacks to ensure a "healthy" DR environment.

 
LVL 65

Expert Comment

by:RobSampson
ID: 34995274
Hi, here's a VBScript.  See how it goes.  It's just that there's not much GUI related stuff to put in a HTA....

Regards,

Rob.
strInput = InputBox("Enter name of file that contains user IDs:", "Input File", "samaccountnames.txt")
strOutput = InputBox("Enter CSV file to save results to:", "Output File", "ValidatedUsers.csv")

Set objFSO = CreateObject("Scripting.FileSystemObject")
Const ForReading = 1
Set objInput = objFSO.OpenTextFile(strInput, ForReading, False)
Set objOutput = objFSO.CreateTextFile(strOutput, True)
objOutput.WriteLine """samAccountName"",""Exists?"",""OU Path"""

While Not objInput.AtEndOfStream
	strSamAccountName = objInput.ReadLine
	If strSamAccountName <> "" Then
		strProperties = Get_LDAP_User_Properties("user", "samaccountname", strsamAccountName, "adsPath")
		If strProperties <> "" Then
			objOutput.WriteLine """" & strSamAccountName & """,""YES"",""" & strProperties & """"
		Else
			objOutput.WriteLine """" & strSamAccountName & """,""NO"","""""
		End If
	End If
Wend
objInput.Close
objOutput.Close

MsgBox "Done. Please see " & strOutput

Function Get_LDAP_User_Properties(strObjectType, strSearchField, strObjectToGet, strCommaDelimProps)
      
      ' This is a custom function that connects to the Active Directory, and returns the specific
      ' Active Directory attribute value, of a specific Object.
      ' strObjectType: usually "User" or "Computer"
      ' strSearchField: the field by which to seach the AD by. This acts like an SQL Query's WHERE clause.
      '				It filters the results by the value of strObjectToGet
      ' strObjectToGet: the value by which the results are filtered by, according the strSearchField.
      '				For example, if you are searching based on the user account name, strSearchField
      '				would be "samAccountName", and strObjectToGet would be that speicific account name,
      '				such as "jsmith".  This equates to "WHERE 'samAccountName' = 'jsmith'"
      '	strCommaDelimProps: the field from the object to actually return.  For example, if you wanted
      '				the home folder path, as defined by the AD, for a specific user, this would be
      '				"homeDirectory".  If you want to return the ADsPath so that you can bind to that
      '				user and get your own parameters from them, then use "ADsPath" as a return string,
      '				then bind to the user: Set objUser = GetObject("LDAP://" & strReturnADsPath)
      
      ' Now we're checking if the user account passed may have a domain already specified,
      ' in which case we connect to that domain in AD, instead of the default one.
      If InStr(strObjectToGet, "\") > 0 Then
            arrGroupBits = Split(strObjectToGet, "\")
            strDC = arrGroupBits(0)
            strDNSDomain = strDC & "/" & "DC=" & Replace(Mid(strDC, InStr(strDC, ".") + 1), ".", ",DC=")
            strObjectToGet = arrGroupBits(1)
      Else
      ' Otherwise we just connect to the default domain
            Set objRootDSE = GetObject("LDAP://RootDSE")
            strDNSDomain = objRootDSE.Get("defaultNamingContext")
      End If
 
      strBase = "<LDAP://" & strDNSDomain & ">"
      ' Setup ADO objects.
      Set adoCommand = CreateObject("ADODB.Command")
      Set adoConnection = CreateObject("ADODB.Connection")
      adoConnection.Provider = "ADsDSOObject"
      adoConnection.Open "Active Directory Provider"
      adoCommand.ActiveConnection = adoConnection
 
 
      ' Filter on user objects.
      'strFilter = "(&(objectCategory=person)(objectClass=user))"
      strFilter = "(&(objectClass=" & strObjectType & ")(" & strSearchField & "=" & strObjectToGet & "))"
 
      ' Comma delimited list of attribute values to retrieve.
      strAttributes = strCommaDelimProps
      arrProperties = Split(strCommaDelimProps, ",")
 
      ' Construct the LDAP syntax query.
      strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
      adoCommand.CommandText = strQuery
      ' Define the maximum records to return
      adoCommand.Properties("Page Size") = 100
      adoCommand.Properties("Timeout") = 30
      adoCommand.Properties("Cache Results") = False
 
      ' Run the query.
      Set adoRecordset = adoCommand.Execute
      ' Enumerate the resulting recordset.
      strReturnVal = ""
      Do Until adoRecordset.EOF
          ' Retrieve values and display.    
          For intCount = LBound(arrProperties) To UBound(arrProperties)
                If strReturnVal = "" Then
                      strReturnVal = adoRecordset.Fields(intCount).Value
                Else
                      strReturnVal = strReturnVal & VbCrLf & adoRecordset.Fields(intCount).Value
                End If
          Next
          ' Move to the next record in the recordset.
          adoRecordset.MoveNext
      Loop
 
      ' Clean up.
      adoRecordset.Close
      adoConnection.Close
      Get_LDAP_User_Properties = strReturnVal
	 
End Function

Open in new window

0
 

Author Comment

by:praveendusi
ID: 34996294
Hi Rob,

You are simply superb.  As awalys, I have seen some of your posts... The scrpits works perfectly.

Just a last question before we close this.  If I want to add anything else apart from the 3 fields?

EX:-  I get the output as "Account Name, Exists?, OT Path".  If I want to add the 4th field say "Created date or Modified Date or Password Modification Date", will that be possible (in Future)?

Many Thanks
Praveen
0
 
LVL 65

Accepted Solution

by:
RobSampson earned 1000 total points
ID: 35003203
You can, as long as the property you want is just a string value.  Some AD properties are array values, and so will need the code to be modified.  For string values, add them by changing this line:

objOutput.WriteLine """samAccountName"",""Exists?"",""OU Path"""

to this

objOutput.WriteLine """samAccountName"",""Exists?"",""OU Path"",""whenCreated"""

and also this line:

            strProperties = Get_LDAP_User_Properties("user", "samaccountname", strSamAccountName, "adsPath")

to this:

            strProperties = Get_LDAP_User_Properties("user", "samaccountname", strSamAccountName, "adsPath,whenCreated")

Regards,

Rob.
strInput = InputBox("Enter name of file that contains user IDs:", "Input File", "samaccountnames.txt")
strOutput = InputBox("Enter CSV file to save results to:", "Output File", "ValidatedUsers.csv")

Set objFSO = CreateObject("Scripting.FileSystemObject")
Const ForReading = 1
Set objInput = objFSO.OpenTextFile(strInput, ForReading, False)
Set objOutput = objFSO.CreateTextFile(strOutput, True)
objOutput.WriteLine """samAccountName"",""Exists?"",""OU Path"""

While Not objInput.AtEndOfStream
	strSamAccountName = objInput.ReadLine
	If strSamAccountName <> "" Then
		strProperties = Get_LDAP_User_Properties("user", "samaccountname", strsamAccountName, "adsPath")
		If strProperties <> "" Then
			objOutput.WriteLine """" & strSamAccountName & """,""YES"",""" & Replace(strProperties, VbCrLf & """,""") & """"
		Else
			objOutput.WriteLine """" & strSamAccountName & """,""NO"","""""
		End If
	End If
Wend
objInput.Close
objOutput.Close

MsgBox "Done. Please see " & strOutput

Function Get_LDAP_User_Properties(strObjectType, strSearchField, strObjectToGet, strCommaDelimProps)
      
      ' This is a custom function that connects to the Active Directory, and returns the specific
      ' Active Directory attribute value, of a specific Object.
      ' strObjectType: usually "User" or "Computer"
      ' strSearchField: the field by which to seach the AD by. This acts like an SQL Query's WHERE clause.
      '				It filters the results by the value of strObjectToGet
      ' strObjectToGet: the value by which the results are filtered by, according the strSearchField.
      '				For example, if you are searching based on the user account name, strSearchField
      '				would be "samAccountName", and strObjectToGet would be that speicific account name,
      '				such as "jsmith".  This equates to "WHERE 'samAccountName' = 'jsmith'"
      '	strCommaDelimProps: the field from the object to actually return.  For example, if you wanted
      '				the home folder path, as defined by the AD, for a specific user, this would be
      '				"homeDirectory".  If you want to return the ADsPath so that you can bind to that
      '				user and get your own parameters from them, then use "ADsPath" as a return string,
      '				then bind to the user: Set objUser = GetObject("LDAP://" & strReturnADsPath)
      
      ' Now we're checking if the user account passed may have a domain already specified,
      ' in which case we connect to that domain in AD, instead of the default one.
      If InStr(strObjectToGet, "\") > 0 Then
            arrGroupBits = Split(strObjectToGet, "\")
            strDC = arrGroupBits(0)
            strDNSDomain = strDC & "/" & "DC=" & Replace(Mid(strDC, InStr(strDC, ".") + 1), ".", ",DC=")
            strObjectToGet = arrGroupBits(1)
      Else
      ' Otherwise we just connect to the default domain
            Set objRootDSE = GetObject("LDAP://RootDSE")
            strDNSDomain = objRootDSE.Get("defaultNamingContext")
      End If
 
      strBase = "<LDAP://" & strDNSDomain & ">"
      ' Setup ADO objects.
      Set adoCommand = CreateObject("ADODB.Command")
      Set adoConnection = CreateObject("ADODB.Connection")
      adoConnection.Provider = "ADsDSOObject"
      adoConnection.Open "Active Directory Provider"
      adoCommand.ActiveConnection = adoConnection
 
 
      ' Filter on user objects.
      'strFilter = "(&(objectCategory=person)(objectClass=user))"
      strFilter = "(&(objectClass=" & strObjectType & ")(" & strSearchField & "=" & strObjectToGet & "))"
 
      ' Comma delimited list of attribute values to retrieve.
      strAttributes = strCommaDelimProps
      arrProperties = Split(strCommaDelimProps, ",")
 
      ' Construct the LDAP syntax query.
      strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
      adoCommand.CommandText = strQuery
      ' Define the maximum records to return
      adoCommand.Properties("Page Size") = 100
      adoCommand.Properties("Timeout") = 30
      adoCommand.Properties("Cache Results") = False
 
      ' Run the query.
      Set adoRecordset = adoCommand.Execute
      ' Enumerate the resulting recordset.
      strReturnVal = ""
      Do Until adoRecordset.EOF
          ' Retrieve values and display.    
          For intCount = LBound(arrProperties) To UBound(arrProperties)
                If strReturnVal = "" Then
                      strReturnVal = adoRecordset.Fields(intCount).Value
                Else
                      strReturnVal = strReturnVal & VbCrLf & adoRecordset.Fields(intCount).Value
                End If
          Next
          ' Move to the next record in the recordset.
          adoRecordset.MoveNext
      Loop
 
      ' Clean up.
      adoRecordset.Close
      adoConnection.Close
      Get_LDAP_User_Properties = strReturnVal
	 
End Function

Open in new window

0
 

Author Closing Comment

by:praveendusi
ID: 35003733
Hi Rob,

Thank you for explaining so as to which part of the script needs to be changed for my future reference.

I appreciate your help and this script has certainly helped me.

I have posted a new question.  Can you please review and see if a solution is possible:

http://www.experts-exchange.com/Software/Server_Software/File_Servers/Active_Directory/Q_26851975.html 

I have few more requirements which I will review and post it here.

Many Thanks
Praveen
0

Featured Post

Is Your AD Toolbox Looking More Like a Toybox?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Here's a look at newsworthy articles and community happenings during the last month.
After seeing many questions for JRNL_WRAP_ERROR for replication failure, I thought it would be useful to write this article.
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

730 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