Remove All Group Memberships for all User Accounts in an OU?

Discussion in 'Scripting' started by Guest, Sep 17, 2008.

  1. Guest

    Guest Guest

    I've seen the examples with


    but it's only one account, I have a whole OU full of accounts whose group
    memberships I need to clear (Domain Users excepted of course). I know I
    can't modify the user account I have to modify the group, because memberof
    is backlinked, but is there a way to essentially loop through the actions of
    the one account and its group memberships, then move to the next user
    account and repeat?

    Any help appreciated
    Guest, Sep 17, 2008
    1. Advertisements

  2. You can enumerate all users in the OU, and for each user enumerate all
    direct group memberships, which will not include the "primary" group (which
    should be "Domain Users"). You can use the Remove method of each group
    object to remove the user from the group. To save binding to each group
    repeatedly for many users, I would track the groups in a dictionary object.
    For example (not tested):
    Option Explicit

    Dim objOU, objUser, arrGroups, strGroup, objGroup
    Dim objGroupList

    ' Bind to OU object.
    Set objOU = GetObject("LDAP://ou=West,dc=MyDomain,dc=com")

    ' Filter on objects of class user.
    objOU.Filter = Array("user")

    ' Create dictionary object of group objects.
    Set objGroupList = CreateObject("Scripting.Dictionary")
    objGroupList.CompareMode = vbTextCompare

    ' Enumerate users in OU.
    For Each objUser In objOU
    ' Enumerate direct group memberships.
    ' Trap error if there are no groups.
    ' Primary group is not included.
    On Error Resume Next
    arrGroups = objUser.GetEx("memberOf")
    If (Err.Number = 0) Then
    On Error GoTo 0
    For Each strGroup In arrGroups
    ' Check if group already bound.
    If (objGroupList.Exists(strGroup) = False) Then
    ' Add group object to the dictionary object.
    Set objGroupList(strGroup) = GetObject("LDAP://" & strGroup)
    End If
    ' Remove user from the group.
    End If
    On Error GoTo 0
    Richard Mueller [MVP], Sep 17, 2008
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.