AD user script

Hi All,
I would like a script that will do the following for a user or users based on excel or text file which ever is easier to script.  It does not have to be in the order below.

-Change password to XXXXX (password will always be the same)
-Add a group membership & set as primary (group will always be the same)
-Remove all other groups except the primary from above step
-Copy Manger info to Notes field under telephone tab
-Remove Manager name
-Remove fax & mobile & ip phone numbers from telephone tab (all fields may not have data)
-Remove telephone from general tab
-Move account to a different OU (This will vary)  

Thanks all for your hard work.   If you have any suggestions, I am open to it.
Who is Participating?
RobSampsonConnect With a Mentor Commented:
Hi, I haven't fully tested this, but change the usernames in the array at the top, and see if it works.  It should do all that you have asked.



arrUsers = Array("user1", "user2")
strPassword = "newpassword"
strNewPrimaryGroup = "CN=New_Group,OU=Our Groups,DC=domain,DC=com"
strNewParentDN = "OU=NewOU,OU=Our OUs,DC=domain,DC=com"


For Each strUserName In arrUsers
	strADSPath = Get_LDAP_User_Properties("user", "samAccountName", strUsername, "adspath")
	If strADsPath <> "" Then
		' Bind to the user
		Set objUser = GetObject(strADsPath)

		' Change the password
		objUser.SetPassword strPassword
		' Set the primary group
		Set objPrimaryGroup = GetObject("LDAP://" & strNewPrimaryGroup)
		objPrimaryGroup.GetInfoEx Array("primaryGroupToken"), 0
		objNewUser.primaryGroupID = objPrimaryGroup.primaryGroupToken

		' Remove from all other groups
		On Error Resume Next
		arrMemberOf = objUser.GetEx("memberOf")
			'WScript.Echo "This account is not a member of any security groups."
			For Each strGroupPath In arrMemberOf
			    Set objGroup = GetObject("LDAP://" & strGroupPath)
			    objGroup.PutEx ADS_PROPERTY_DELETE, "member", Array(objUser.distinguishedName)
		End If

		' Put manager name into Notes field (info)
		strManager = objUser.manager
		If strManager <> "" Then = strManager
			' Remove the manager
			objuser.PutEx ADS_PROPERTY_CLEAR, "Manager", 0
		End If
		' Remove fax, mobile, and IP numbers
		objUser.facsimileTelephoneNumber = ""
		objUser.ipPhone = "" = ""
		' Remove telephone number from General tab
		objUser.telephoneNumber = ""
		' Move the user to a new account
		Set objNewOU = GetObject(strNewParentDN)
		objNewOU.MoveHere "LDAP://" & objUser.distinguishedName, vbNullString
	End If

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)
    ' 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
                If IsArray(adoRecordset.Fields(intCount).Value) Then
                    For Each strValue In adoRecordset.Fields(intCount).Value
                        If strReturnVal = "" Then
                            strReturnVal = strValue
                            strReturnVal = strReturnVal & ", " & strValue
                        End If
                    strReturnVal = adoRecordset.Fields(intCount).Value
                End If
                If IsArray(adoRecordset.Fields(intCount).Value) Then
                    For Each strValue In adoRecordset.Fields(intCount).Value
                        strReturnVal = strReturnVal & ", " & strValue
                    strReturnVal = strReturnVal & ", " & adoRecordset.Fields(intCount).Value
                End If
            End If
        ' Move to the next record in the recordset.
    ' Clean up.
    Get_LDAP_User_Properties = strReturnVal
End Function

Open in new window

@keonh - I don't want to sound too harsh, but...
It always irks me when I see someone asking for a complete script that does more than one or two things.  People get paid good money to write custom stuff like that.  I understand that people have different skill sets and may not have experience as a scripter, but when something this specific is required they should try to learn and contribute to the solution or hire a consultant to do it for them.  I love helping people out at this site, but I don't like doing their job for them.  Good luck.
Yes agreeing to foot tech this is something a complete help.If thats the issues then why are you searching, opt a third party tool that will make your work easier.

If you would ask to give a script on password update or name update then this would be the best part to explain you up.Same like on all of your issues.

Tony MassaCommented:
Here's a sample script that works well.  Customize to fit your needs.

You should probably try to learn PowerShell as it will be the defacto scripting language for years to come... has a lot of very good examples in VB and PS.
keonhAuthor Commented:
Thanks everyone!!!!  I will test them & see what happens.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.