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 42

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

Easily manage email signatures in Office 365

Managing email signatures in Office 365 can be a challenging task if you don't have the right tool. CodeTwo Email Signatures for Office 365 will help you implement a unified email signature look, no matter what email client is used by users. Test it for free!

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.

Join & Write a Comment

Wouldn't it be nice if objects in Active Directory automatically moved into the correct Organizational Units? This is what AutoAD aims to do and as a plus, it automatically creates Sites, Subnets, and Organizational Units.
Sometimes it necessary to set special permissions on user objects.  For instance when using a Blackberry server, the SendAs permission needs to be set. I see many admins struggle with the setting that permission only to see it disappear within a few…
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

624 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