AD user script

Posted on 2013-01-27
Medium Priority
Last Modified: 2014-10-28
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.
Question by:keonh
LVL 41

Expert Comment

ID: 38825578
@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.

Expert Comment

ID: 38826075
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.

LVL 17

Expert Comment

by:Tony Massa
ID: 38829729
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...http://www.rlmueller.net/ has a lot of very good examples in VB and PS.
LVL 65

Accepted Solution

RobSampson earned 2000 total points
ID: 38829848
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
			objUser.info = strManager
			' Remove the manager
			objuser.PutEx ADS_PROPERTY_CLEAR, "Manager", 0
		End If
		' Remove fax, mobile, and IP numbers
		objUser.facsimileTelephoneNumber = ""
		objUser.ipPhone = ""
		objUser.mobile = ""
		' 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


Author Comment

ID: 38853192
Thanks everyone!!!!  I will test them & see what happens.

Featured Post

Making Bulk Changes to Active Directory

Watch this video to see how easy it is to make mass changes to Active Directory from an external text file without using complicated scripts.

Question has a verified solution.

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

Recently, Microsoft released a best-practice guide for securing Active Directory. It's a whopping 300+ pages long. Those of us tasked with securing our company’s databases and systems would, ideally, have time to devote to learning the ins and outs…
Active Directory can easily get cluttered with unused service, user and computer accounts. In this article, I will show you the way I like to implement ADCleanup..
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 …
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …
Suggested Courses

862 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