Ok, I've been going through a bunch of vbs scripts that a previous consultant at my current client wrote. Most of the scripts actually work fairly well but trying to follow what they are doing can be difficult and they can be a real pain to update. Some of the cleanup has been fairly complicated but there are a few simple things that I've done that make the code a lot more flexible and a lot easier to understand. Hopefully I'll be able to leave my client with some scripts that they can support themselves when I am gone.
Here's an example of how a simple subroutine/function can make things easier:
Old Code Fragment: (basically just adding attributes to a user account)
objUser.Put "userPrincipalName", strUserName & "@ds.ad.ssmhc.com"
objUser.SetInfo
If err.number <> 0 Then
strRet = err.number
Call ExceptionHandler("Error in LDAP set info userPrincipalName" & err.number & " Desc: " & err.Description)
End If
objUser.Put "title", strJobTitle
If err.number <> 0 Then
strRet = err.number
Call ExceptionHandler("Error in LDAP set info userPrincipalName" & err.number & " Desc: " & err.Description)
End If
objUser.SetInfo
If err.number <> 0 Then
strRet = err.number
Call ExceptionHandler("Error in LDAP set info userPrincipalName" & err.number & " Desc: " & err.Description)
End If
objUser.Put "givenName", strFirstName
If err.number <> 0 Then
strRet = err.number
Call ExceptionHandler("Error in LDAP put givenName" & err.number & " Desc: " & err.Description)
End If
etc.....There were a number of other attributes getting set in the code (100+ lines of code required)
By creating a function that allows you to pass the attribute you are updating and the value you want to set it to you will have code that is easy to update and much easier to understand
New Code Fragment:
Call SetAccountAttribute(objUser, "userPrincipalName", strUserName & "@ds.ad.ssmhc.com")
Call SetAccountAttribute(objUser, "title", strJobTitle)
Call SetAccountAttribute(objUser, "givenName", strFirstName)
Call SetAccountAttribute(objUser, "initials", strMiddleInitial)
Function SetAccountAttribute(objUser, strAttributeName, strAttributeValue)
objUser.Put strAttributeName, strAttributeValue
objUser.SetInfo
If err.number <> 0 Then
strRet = err.number
Call ExceptionHandler("Error in LDAP set info: " & strAttributeName & vbTab & _
vbTab & err.number & " Desc: " & err.Description)
End If
End Function
In this case I could've used a subroutine instead of a function since I am not actually returning any values but I'll probably add that functionality in at some point down the road. By having all of the “smarts“ in a function I have one place that I can make changes instead of the 15 that I would've had before. Plus, the number of lines required dropped from over 100 to less than 20.