Solved

LDAP WSH Find User in AD

Posted on 2006-11-16
8
554 Views
Last Modified: 2008-02-01
I need to search for an AD User in the my Domain but dont want it to be specific to any OU, and would also rather it determine what the Domain is?
Any ideas?
0
Comment
Question by:dion_p1
  • 4
  • 4
8 Comments
 
LVL 70

Expert Comment

by:Chris Dent
Comment Utility

What terms do you want to search by?

And how would you have it grab the domain name? There are a number of methods you can use, but to get the domain name automatically you would have to be logged onto the domain you're searching. Is that the case?

Chris
0
 

Author Comment

by:dion_p1
Comment Utility
The script will be scheduled on the Domain Controller, but i dont want it to depend on it being on the DC either. I Can tell you that what ever machine it will run on it will be a member of the domain.

The idea is to find the user if it exist by first searching for the OU it will be in.
strOU="SecInClass"
The OU will be strOU

Then search for the Username in that OU. The username will be strUserID.
0
 
LVL 70

Expert Comment

by:Chris Dent
Comment Utility

As long as you're on the domain you're fine. It's just when you're trying to search outside the domain you're connected to that everything becomes tricky (you can't connect to a database you know nothing at all about).

Anyway, there are a few different ways depending on exactly what you have. You can connect to the OU itself if you specify the path (using the RootDSE object to get the naming context for the current domain):

Set objRootDSE = GetObject("LDAP://RootDSE")
Set objOU = GetObject("LDAP://" & strOU & "," & objRootDSE.Get("defaultNamingContext"))

Once connected you can loop through the users:

objOU.Filter = Array("user")
For Each objUser in objOU
   ...
Next

The drawback with this method is that you would need to specify the full LDAP path for the OU - that might not be so fun.

So alternatives: If you have the UserID you can use the Name Translate Object, in this case the catch is that the one performing the search must be an Administrator. Here's a bit of sample code:

Const ADS_NAME_INITTYPE_GC = 3
Const ADS_NAME_TYPE_1779 = 1
Const ADS_NAME_TYPE_NT4 = 3

Set objNameTranslate = CreateObject("NameTranslate")

Set objNetwork = CreateObject("WScript.Network")
strDomain = objNetwork.UserDomain
Set objNetwork = Nothing

objNameTranslate.Init ADS_NAME_INITTYPE_GC, ""
objNameTranslate.Set ADS_NAME_TYPE_NT4, strDomain & "\" & strUserID
strUserDN = objNameTranslate.Get(ADS_NAME_TYPE_1779)

Set objNameTranslate = Nothing


This method uses the WScript.Network Object to pick up the current domain, then gets the Distinguished Name for a User from the UserID (SAMAccountName).

I'll post about ADODB and searching in a sec, just need to fix a few things here. We can cover recursion through AD as well if you wish.

Chris
0
 

Author Comment

by:dion_p1
Comment Utility
you Lost me....

I think your posting in two of my question both essentially the same question.
Any way if you can help great you have all the points you want im at a dead end with this part of my works requirements.

So difficultly not basicly im trying to create a script that creates users in my domain for me.....

The script already reads all the user info from a csv file that is needed, all i need to do now is make it so that it actually create the users.
Im thinking that if i get the script to determine the OU its supposed to create the usern in then i can get it to do the rest. Determining the OU is the hard part.

The OU will be determined by two things
The strOU will be defined by the user of the script, they will be told that for Year 1 through Year 3 Users they have to specify the name of the OU.

strOUY1="Year1"
strOUY2="Year2"
strOUY3="Year3"

strYear will be in the csv file. This is the year of the user. I want to make it so that 01 = strOUY1 and 02 = strOUY2 etc......
i think that will work something like this

if strYear = "01" then
strOU = strOUY1
elseif strYear = "02" then
strOU = strOUY2
elseif strYear = "03" then
strOU = strOUY3
end if

Then the script should do something like this

1.Connect to Domain
2.Find strYear (Find the OU Defined by Script User)
3.Search for strUserID
4.If strUserID Found msgbox "User Found"
5.If Not Found then Create User


0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 70

Expert Comment

by:Chris Dent
Comment Utility

Okay, sounds fair enough to me. This is a heavily commented version that hopefully describes everything the script does. For simplicity I've used Recursion to find the OU it needs.


' Forces us to Declare variables, good to ensure everything is working in the correct scope.

Option Explicit

' User Defined Constants

Const YEAR_1 = "Year1"
Const YEAR_2 = "Year2"
Const YEAR_3 = "Year3"

' Functions

Function FindObject(strObjectName, strDN)
      Dim objRootDSE, objOU, objSubOU
      Dim strResult
      
      If strDN = "" Then
            Set objRootDSE = GetObject("LDAP://RootDSE")
            Set objOU = GetObject("LDAP://" & objRootDSE.Get("defaultNamingContext"))
            Set objRootDSE = Nothing
      Else
            Set objOU = GetObject("LDAP://" & strDN)
      End If
      
      objOU.Filter = Array("organizationalUnit")

      For Each objSubOU in objOU
            If objSubOU.Get("name") = strObjectName Then
                  strResult = objSubOU.Get("distinguishedName")
            ElseIf strResult = "" Then
                  strResult = FindObject(strObjectName, objSubOU.Get("distinguishedName"))
            End If
      Next
      FindObject = strResult
End Function

'
' Main Code
'

' Variables

Dim objRootDSE, objOU, objUser, objNetwork
Dim strYear, strDN, strDomain, strUserName

' Select is just neater and shorter for this. : is used to replace a normal line break in the script to keep it neat.
' strYear needs to be populated with one of these values before this is called.

Select Case strYear
      Case "01" : strYear = YEAR_1
      Case "02" : strYear = YEAR_2
      Case "03" : strYear = YEAR_3
End Select

' Find the OU - Calls the FindObject subroutine above - That deals with connecting to the current domain.
' It uses Recursion to find it. strDN will be blank if it can't be found. There is one limitation with the
' current version, it will not find OUs under the default Users folder (as this is Container class not
' organizationalUnit).

strDN = FindObject(strYear, "")

' Searching for User ID. We use this method because you can't duplicate the SAMAccountName within the
' domain without upsetting it. strUserName must be populated by this point - from CSV I assume.

Set objNetwork = CreateObject("WScript.Network")

On Error Resume Next : Err.Clear
Set objUser = GetObject("WinNT://" & objNetwork.UserDomain & "/" & strUserName & ", user")
If Err.Number = 0 Then
      MsgBox "User Found"
      WScript.Quit
End If
On Error Goto 0

Set objNetwork = Nothing

' Connect to the OU and Create a User - This demonstrates filling in a few other bits of information.
' Everything is based around the Username at the moment, it's all flexible though and depends on what
' you have in the CSV.

Set objRootDSE = GetObject("LDAP://RootDSE")
strDomain = Replace(objRootDSE.Get("defaultNamingContext"), ",DC=", ".")
strDomain = Replace(strDomain, "DC=", "")
Set objRootDSE = Nothing

' The Users container name must begin with CN= this one just uses the UserID for this.

Set objOU = GetObject("LDAP://" & strDN)
Set objUser = objOU.Create("user", "CN=" & strUserName)
objUser.SetInfo

' A few other attributes:

objUser.Put "sAMAccountName", strUserName
objUser.Put "displayName", strUserName
objUser.Put "userPrincipalName", strUserName & "@" & strDomain
objUser.SetInfo

objUser.SetPassword "NewUserPassword"

' Get rid of the Objects we have - especially important if you're looping and creating multiple users.

Set objUser = Nothing
Set objOU = Nothing
0
 

Author Comment

by:dion_p1
Comment Utility
I have attempted puting this in my code. But when i attempt to run it it errors at "This Line Set objUser = objOU.Create("user", "CN=" & strUserName)"

See my Full Script Below....

'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
'Dont Edit Above
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
   
          strInputFile = "C:\Working\"
      strExportFile = "C:\Working\"
      logfpath = "C:\Working\"
          strEmailOk = "YES"
          strExchangeSrv = "XX.XX.XX.XX"
      strEmailFrm = "UserEmail@Domain.com"
      strEmailTo = "UserEmail@Domain.com"
      strEmailAttachment = "C:\Working\"
      strEmailSub = "New User Added to Network "
      strEmailBody = "See Attached for New Users and Password Created on "

      Const YEAR_1 = "Year 1"
      Const YEAR_2 = "Year 2"
      Const YEAR_3 = "Year 3"

'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
'Dont Edit Below
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Dim objContainer, objFileSys, strpassword, strExit, strEnter, strEmailOk
Dim strDomainOU, strRtn, strUserID, strFirstname, strSurname, strGroup, strUserPath, strCACLS, strMKDIR
Dim strInputFile, objInputFile, strInputData, strData, strCampus, strHomeFolder, rootDSE, domainObject, domainContainer
Dim objRootDSE, objOU, objUser, objNetwork
Dim strYear, strDN, strDomain, strUserName
Set objFileSys = Wscript.CreateObject("Scripting.FileSystemObject")
Set objShell = CreateObject("Wscript.Shell")
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
'Current Date Function
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
strCDate = Now()
strCDate = Day(strCDate) & "-" & Month(strCDate) & "-" & Year(strCDate)
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
'Open Log File
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    Dim txtfilObject
    Dim logfpath
    Set logfile = objfilesys.CreateTextFile(logfpath & strcDate & " AutoUserImport.log", True)
    logfile.WriteLine ("Log File Created " & logfpath & strcDate & " AutoUserImport.log")
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
'Read Original Export and Add Random Passwords
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Set oInputFile = objFileSys.OpenTextFile(strInputFile & strcDate & " ExportFromCases.csv")
strInputData = Split(oInputFile.ReadAll, vbNewline)
      logfile.WriteLine ("Opening Cases Original Export " & strInputFile & strcDate & " ExportFromCases.csv")
On Error Resume Next
For each strData In strInputData
     Set file = objFileSys.CreateTextFile(strExportFile & strCDate & " ExportWithPasswords.csv",TRUE)
     file.writeline(strData & "," & Right("00000" & Int(Rnd()*1000000), 6))
     strUserID= Ucase(split(strData, ",") (0))
           logfile.WriteLine ("Generating Password For " &  strUserID & " Saving Data to " & strExportFile & strCDate & " ExportWithPasswords.csv")
Next
file.close
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
'Read ExportWithPasswords
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Set oInputFile = objFileSys.OpenTextFile(strExportFile)
strInputData = Split(oInputFile.ReadAll, vbNewline)
On Error Resume Next
For each strData In strInputData
          strUserID= Ucase(split(strData, ",") (0))
          strFirstname = Lcase(split(strData, ",") (1))
          strFirstname = Ucase(left(strFirstname, 1)) & mid(strFirstname, 2, len(strFirstname))
          strSurname = Lcase(split(strData, ",") (2))
          strSurname = Ucase(left(strSurname, 1)) & mid(strSurname, 2, len(strSurname))
          strSurname = Replace(strSurname, "'", "")
          strGroup = Ucase(split(strData, ",") (3))
          strYear = Lcase (Split(strData, ",") (4))
          strHomeFolder = Lcase(split(strData, ",")(4))
      strEnter = LCase(Split(strData, ",")(5))
      strExit = LCase (Split(strData, ",")(6))
      strPassword = Lcase(split(strData, ",")(7))
           logfile.WriteLine ("Reading User Information " & strUserID & " From " & strCDate & " ExportWithPasswords.csv")
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
'Create User after Finding OU
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

' Select is just neater and shorter for this. : is used to replace a normal line break in the script to keep it neat.
' strYear needs to be populated with one of these values before this is called.

Select Case strYear
     Case "01" : strYear = YEAR_1
     Case "02" : strYear = YEAR_2
     Case "03" : strYear = YEAR_3
End Select

' Find the OU - Calls the FindObject subroutine above - That deals with connecting to the current domain.
' It uses Recursion to find it. strDN will be blank if it can't be found. There is one limitation with the
' current version, it will not find OUs under the default Users folder (as this is Container class not
' organizationalUnit).

strDN = FindObject(strYear, "")

' Searching for User ID. We use this method because you can't duplicate the SAMAccountName within the
' domain without upsetting it. strUserName must be populated by this point - from CSV I assume.

Set objNetwork = CreateObject("WScript.Network")

On Error Resume Next : Err.Clear
Set objUser = GetObject("WinNT://" & objNetwork.UserDomain & "/" & strUserName & ", user")
If Err.Number = 0 Then
     MsgBox "User Found"
     WScript.Quit
End If
On Error Goto 0

Set objNetwork = Nothing

' Connect to the OU and Create a User - This demonstrates filling in a few other bits of information.
' Everything is based around the Username at the moment, it's all flexible though and depends on what
' you have in the CSV.

Set objRootDSE = GetObject("LDAP://RootDSE")
strDomain = Replace(objRootDSE.Get("defaultNamingContext"), ",DC=", ".")
strDomain = Replace(strDomain, "DC=", "")
Set objRootDSE = Nothing

' The Users container name must begin with CN= this one just uses the UserID for this.
Set objOU = GetObject("LDAP://" & strDN)
Set objUser = objOU.Create("user", "CN=" & strUserName)
objUser.SetInfo

' A few other attributes:

objUser.Put "sAMAccountName", strUserName
objUser.Put "displayName", strUserName
objUser.Put "userPrincipalName", strUserName & "@" & strDomain
objUser.SetInfo

objUser.SetPassword "NewUserPassword"

' Get rid of the Objects we have - especially important if you're looping and creating multiple users.

Set objUser = Nothing
Set objOU = Nothing
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
'Next Record
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Next
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
'Email If strEmailOk = Yes
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if strEmailOk = "YES" then
           logfile.WriteLine ("Sending Email to " & strEmailTo & " With Attachment " & strEmailAttachment & strCDate & " ExportWithPasswords.csv")
Call EmailUser
Else
End If
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
'Email Action Sub
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Sub EmailUser
Const cdoSendUsingMethod = "http://schemas.microsoft.com/cdo/configuration/sendusing", _
cdoSendUsingPort = 2, _
cdoSMTPServer = "http://schemas.microsoft.com/cdo/configuration/smtpserver"
'Create the CDO connections.
Dim iMsg, iConf, Flds
Set iMsg = CreateObject("CDO.Message")
Set iConf = CreateObject("CDO.Configuration")
Set Flds = iConf.Fields
'SMTP server configuration.
With Flds
.Item(cdoSendUsingMethod) = cdoSendUsingPort
'Set the SMTP server address here.
.Item(cdoSMTPServer) = strExchangeSrv
.Update
End With
'Set the message properties.
With iMsg
Set .Configuration = iConf
.To = strEmailTo
.From = strEmailFrm
.Subject = strEmailSub & strCDate
.TextBody = strEmailBody & strCDate
End With
'An attachment can be included.
iMsg.AddAttachment strEmailAttachment & strCDate & " ExportWithPasswords.csv"
'Send the message.
iMsg.Send ' send the message.
End Sub
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
'Find OU Function
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Function FindObject(strObjectName, strDN)
     Dim objRootDSE, objOU, objSubOU
     Dim strResult
     
     If strDN = "" Then
          Set objRootDSE = GetObject("LDAP://RootDSE")
          Set objOU = GetObject("LDAP://" & objRootDSE.Get("defaultNamingContext"))
          Set objRootDSE = Nothing
     Else
          Set objOU = GetObject("LDAP://" & strDN)
     End If
     
     objOU.Filter = Array("organizationalUnit")

     For Each objSubOU in objOU
          If objSubOU.Get("name") = strObjectName Then
               strResult = objSubOU.Get("distinguishedName")
          ElseIf strResult = "" Then
               strResult = FindObject(strObjectName, objSubOU.Get("distinguishedName"))
          End If
     Next
     FindObject = strResult
End Function
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
'Close Script
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
logfile.WriteLine ("Log File Close and Save " & logfpath & strcDate & " AutoUserImport.log")
logfile.Close
wscript.close


0
 
LVL 70

Accepted Solution

by:
Chris Dent earned 500 total points
Comment Utility

We need to make a few modifications to have that all fit in neatly with your script. At present it'll quit the moment it finds an existing user (and just not do anything with the rest). The problem above is caused by a difference in naming conventions between us, I call it strUsername, you call it strUserID.

Anyway, this is a fixed version (as long as I didn't make any typo's). These are the changes:

 - Added Option Explicit. All variables must be correctly declared.
 - Moved Checking for Existing User into a Function. Made it log this into the Log File.
 - Email Subroutine has been revised slightly and moved.
 - Variables at the beginning of the script have been revised and switched to Constants
 - All file names are generated once only and referred to only by that name afterwards for ease of maintainance.
 - Fixed a problem while Writing the Password Export file from the original - would have resulted in a file containing only the last entry from CasesExport (Created Password Export File within Looped Read of Cases File)
 - Removed all the Split statements while Reading the PasswordExport File so it's only done once (into arrData). Saves time and energy.
 - Changed Container Name for new User to be "Firstname Surname" instead of UserID. Aesthetic change really.
 - Populated HomeDirectory and HomeDrive fields. HomeDrive is a Constant at the beginning on the script as it isn't mentioned in the Export.

I think that's everything. Let me know if you have any questions about it all.

Chris



Option Explicit

'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
'Dont Edit Above
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Const WORKING_DIRECTORY = "C:\Working\"
Const LOG_FILE_PATH = "C:\Working\"

Const EXCHANGE_SERVER = "XX.XX.XX.XX"

Const SEND_EMAIL = "YES"
Const EMAIL_FROM = "UserEmail@Domain.com"
Const EMAIL_TO = "UserEmail@Domain.com"
Const EMAIL_SUBJECT = "New User Added to Network "
Const EMAIL_BODY = "See Attached for New Users and Password Created on "

Const HOME_DRIVE = "H:"

Const YEAR_1 = "Year 1"
Const YEAR_2 = "Year 2"
Const YEAR_3 = "Year 3"

'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
'Dont Edit Below
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

'
' Functions
'

Function UserExists(strUserName)
      ' Searching for User ID. We use this method because you can't duplicate the SAMAccountName within the
      ' domain without upsetting it.
      
      Dim objNetwork, objUser
      Dim booUserExists

      booUserExists = False

      On Error Resume Next : Err.Clear

      Set objNetwork = CreateObject("WScript.Network")
      Set objUser = GetObject("WinNT://" & objNetwork.UserDomain & "/" & strUserName & ", user")
      If Err.Number = 0 Then
            MsgBox "User Found " & strUserID
            objLogFile.WriteLine "User Already Exists " & strUserID
            booUserExists = True
      End If
      On Error Goto 0
      Set objUser = Nothing
      Set objNetwork = Nothing
      
      UserExists = booUserExists
End Function

Function FindObject(strObjectName, strDN)
      ' Finds an OU Object within AD by Name

      Dim objRootDSE, objOU, objSubOU
      Dim strResult
      
      If strDN = "" Then
            Set objRootDSE = GetObject("LDAP://RootDSE")
            Set objOU = GetObject("LDAP://" & objRootDSE.Get("defaultNamingContext"))
            Set objRootDSE = Nothing
      Else
            Set objOU = GetObject("LDAP://" & strDN)
      End If
      
      objOU.Filter = Array("organizationalUnit")

      For Each objSubOU in objOU
            If objSubOU.Get("name") = strObjectName Then
                  strResult = objSubOU.Get("distinguishedName")
            ElseIf strResult = "" Then
                  strResult = FindObject(strObjectName, objSubOU.Get("distinguishedName"))
            End If
      Next
      FindObject = strResult
End Function

'
' Subroutines
'

Sub EmailUser
      ' Sends out an Email

      Dim objMail

      Set objMail = CreateObject("CDO.Message")

      objMail.From = EMAIL_FROM
      objMail.To = EMAIL_TO
      objMail.Subject = EMAIL_SUBJECT & strCDate
      objMail.TextBody = EMAIL_BODY & strCDate

      'An attachment can be included.
      objMail.AddAttachment strPasswordExport

      objMail.Configuration.Fields.Item _
            ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
      objMail.Configuration.Fields.Item _
            ("http://schemas.microsoft.com/cdo/configuration/smtpserver") _
            = EXCHANGE_SERVER
      objMail.Configuration.Fields.Item _
            ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") _
            = 25

      objMail.Configuration.Fields.Update

      objMail.Send
      Set objMail = Nothing
End Sub

'
' Main Code
'

' Global Variables

Dim objFileSys, objLogFile, objInputFile, objFile, objRootDSE, objOU, objUser
Dim strCDate, strLogFile, strExportFromCases, strPasswordExport, strData
Dim strUserID, strFirstName, strSurname, strGroup, strYear, strHomeFolder
Dim strEnter, strExit, strPassword, strDN, strDomain
Dim arrInputData, arrData

' Global Objects

Set objFileSys = CreateObject("Scripting.FileSystemObject")

' Generate and Store all Filenames - Saves repetition

strCDate = Day(Date) & "-" & Month(Date) & "-" & Year(Date)
strLogFile = WORKING_DIRECTORY & strCDate & " AutoUserImport.log"
strExportFromCases = WORKING_DIRECTORY & strCDate & " ExportFromCases.csv"
strPasswordExport = WORKING_DIRECTORY & strCDate & " ExportWithPasswords.csv"

' Create the LogFile Object

Set objLogFile = objFileSys.CreateTextFile(strLogFile, True)
objLogFile.WriteLine "Log File Created " & strLogFile

' Connect to the Import File and read everything into the Array InputData

objLogFile.WriteLine "Opening Cases Original Export " & strExportFromCases

Set objInputFile = objFileSys.OpenTextFile(strExportFromCases)
arrInputData = Split(objInputFile.ReadAll, vbNewline)
Set objInputFile = Nothing

' Create the new Export File with Passwords added

Set objFile = objFileSys.CreateTextFile(strPasswordExport, True)
On Error Resume Next
For Each strData In arrInputData
      objFile.writeline(strData & "," & Right("00000" & Int(Rnd()*1000000), 6))
      
      strUserID = UCase(Split(strData, ",")(0))

      objLogFile.WriteLine "Generating Password For " &  strUserID & " Saving Data to " strPasswordExport
Next
objFile.Close
Set objFile = Nothing

' Reattach to the Password File for Reading

Set objInputFile = objFileSys.OpenTextFile(strPasswordExport)
arrInputData = Split(objInputFile.ReadAll, vbNewline)

For each strData In arrInputData
      objLog.WriteLine ("Reading User Information " & strUserID & " From " & strPasswordExport)

      ' The following are not currently used:
      ' strGroup, strEnter, strExit

      arrData = Split(strData, ",")

      strUserID = Ucase(arrData(0))
      strFirstname = Lcase(arrData(1))
      strFirstname = UCase(Left(strFirstname, 1)) & Mid(strFirstname, 2, Len(strFirstname))
      strSurname = LCase(arrData(2))
      strSurname = UCase(Left(strSurname, 1)) & Mid(strSurname, 2, Len(strSurname))
      strSurname = Replace(strSurname, "'", "")
      strGroup = UCase(arrData(3))
      strYear = LCase (arrData(4))
      strHomeFolder = LCase(arrData(4))
      strEnter = LCase(arrData(5))
      strExit = LCase (Split(arrData(6))
      strPassword = Lcase(arrData(7))
            
      ' Select is just neater and shorter for this. : is used to replace a normal line break in the script to keep it neat.
      ' strYear needs to be populated with one of these values before this is called.
      
      Select Case strYear
            Case "01" : strYear = YEAR_1
            Case "02" : strYear = YEAR_2
            Case "03" : strYear = YEAR_3
      End Select
      
      ' Find the OU - Calls the FindObject subroutine above - That deals with connecting to the current domain.
      ' It uses Recursion to find it. strDN will be blank if it can't be found. There is one limitation with the
      ' current version, it will not find OUs under the default Users folder (as this is Container class not
      ' organizationalUnit).
      
      strDN = FindObject(strYear, "")

      ' Only do the next bit if the User doesn't exist and we've managed to find the OU it goes into
      
      If UserExists(strUserID) = False And strDN <> "" Then

            ' Connect to the OU and Create a User - This demonstrates filling in a few other bits of information.
            ' Everything is based around the Username at the moment, it's all flexible though and depends on what
            ' you have in the CSV.
            
            Set objRootDSE = GetObject("LDAP://RootDSE")
            strDomain = Replace(objRootDSE.Get("defaultNamingContext"), ",DC=", ".")
            strDomain = Replace(strDomain, "DC=", "")
            Set objRootDSE = Nothing
            
            ' The Users container name must begin with CN=. Generated from the GivenName and Surname.
            
            Set objOU = GetObject("LDAP://" & strDN)
            Set objUser = objOU.Create("user", "CN=" & strFirstName & " " & strSurname)
            objUser.SetInfo
            
            ' Setup all the name entries
            
            objUser.Put "sAMAccountName", strUserID
            objUser.Put "givenName", strFirstName
            objUser.Put "sN", strSurname
            objUser.Put "displayName", strFirstName & " " & strSurname
            objUser.Put "userPrincipalName", strUserID & "@" & strDomain
            objUser.SetInfo
            
            ' Setup the Home Directory information
            
            objUser.Put "homeDrive", HOME_DRIVE
            objUser.Put "homeDirectory", strHomeFolder
            objUser.SetInfo
            
            ' Set the new password
            
            objUser.SetPassword strPassword
            
            ' Get rid of the Objects we have - especially important as we're looping and creating multiple users.
            
            Set objUser = Nothing
            Set objOU = Nothing
      End If
Next

' Send out an Email with the new users and their passwords

If SEND_EMAIL = "YES" Then
      objLogFile.WriteLine "Sending Email to " & strEmailTo & " With Attachment " strPasswordExport
      EmailUser
End If

' Log File and FileSystemObject

objLogFile.WriteLine "Log File Close and Save " & strLogFile
objLogFile.Close

Set objLogFile = Nothing
Set objFileSys = Nothing



0
 

Author Comment

by:dion_p1
Comment Utility
Thankyou so much, please do me this favour, go to this question and continue helping me with this i will post as many questions as needed...

http://www.experts-exchange.com/Programming/Programming_Languages/Visual_Basic/Q_22064406.html
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Have you ever wanted to restrict the users input in a textbox to numbers, and while doing that make sure that they can't 'cheat' by pasting in non-numeric text? Of course you can do that with code you write yourself but it's tedious and error-prone …
Most everyone who has done any programming in VB6 knows that you can do something in code like Debug.Print MyVar and that when the program runs from the IDE, the value of MyVar will be displayed in the Immediate Window. Less well known is Debug.Asse…
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

771 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

10 Experts available now in Live!

Get 1:1 Help Now