Quantcast

P^i

Your Online Tech Magazine

Mon05202013

Last update06:24:47 AM

Back You are here: Home More Programming and Web Programming VBScript: How Can I Add a User to a Group, but Only if that User is a Member of the IT Department?

VBScript: How Can I Add a User to a Group, but Only if that User is a Member of the IT Department?



Well, for starters, you get a script like this one, which adds the user Jack Richins to the group IT Staff … provided, of course, that Jack is a member of the IT department:

 

Set objUser = GetObject("LDAP://cn=Jack Richins,ou=canada,dc=fabrikam,dc=com")

If objUser.Department = "IT" Then
    Set objGroup = GetObject _
        ("LDAP://cn=IT Staff,ou=support,dc=fabrikam,dc=com")
    objGroup.Add(objUser.ADsPath)
End If

 

As you can see, this is a simple little script. We begin by using this line of code to bind directly to Jack Richins’ user account in Active Directory:

 

Set objUser = GetObject("LDAP://cn=Jack Richins,ou=canada,dc=fabrikam,dc=com")

 

We then check to see whether or not Jack’s Department attribute is equal to IT:

 

If objUser.Department = "IT" Then

 

Let’s assume that it is. In that case, we then create a second object reference, one that connects us to the IT Staff group account:

 

Set objGroup = GetObject _
    ("LDAP://cn=IT Staff,ou=support,dc=fabrikam,dc=com")

 

Once we’ve made that connection we can then call the Add method (passing the value of Jack’s ADsPath attribute as the sole parameter) and add Jack to the group. If Jack isn’t part of the IT department then we don’t do anything at all.

 

Not bad, huh? Now here’s the bonus script. This script searches Active Directory and returns a list of all the users (objectCategory='user') who happen to be members of the IT department (Department=’IT’). For each user meeting those criteria (that is, each user in the IT department), the script adds the user to the IT Staff group:

 

On Error Resume Next

Const ADS_SCOPE_SUBTREE = 2

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE

objCommand.CommandText = _
    "SELECT ADsPath FROM 'LDAP://dc=fabrikam,dc=com' WHERE objectCategory='user' " & _
         "AND Department='IT'"
Set objRecordSet = objCommand.Execute

objRecordSet.MoveFirst

Set objGroup = GetObject _
    ("LDAP://cn=IT Staff,ou=support,dc=fabrikam,dc=com")

Do Until objRecordSet.EOF
    objGroup.Add(objRecordSet.Fields("ADsPath").Value)
    objRecordSet.MoveNext
Loop

 

Basics of VBScript can be found here








blog comments powered by Disqus