preload

Active Directory Scripting – Security Group membership

Posted by Albert Gareev on Mar 11, 2010 | Categories: Back-endSource code

Reference page: Active Directory – Sample Scripts (Excel/VBA) 

Description 

The function below is used to clear group membership for a user account. The account is removed from all groups except recognized ones . By default, “Users” and “Domain Users” are in the list. The function can be easily modifed to recognize and process membership based on different types of groups: list to exclude, list to keep, list to warn, etc.

The function returns FALSE if any LDAP operation is failed.


Private Function ClearUserGroups(ByRef objUser)
Dim boolRC, intRC
Dim objGroup
Dim sUserPath
Dim sGroupName, sGroupCode, sGroupPrefix

'Get LDAP path for the User
On Error Resume Next
sUserPath = objUser.Get("distinguishedName")
boolRC = (Err.Number <> 0)
On Error GoTo 0
'Error-handling
If boolRC Then
    ClearUserGroups = False
    Exit Function
End If

For Each objGroup In objUser.Groups
    sGroupName = UCase(Mid(objGroup.Name, 4))

 
    Do While True

 
        'excluding allowed groups
        If sGroupName = "USERS" Then
            Exit Do
        End If
        If sGroupName = "DOMAIN USERS" Then
            Exit Do
        End If
        
        'Removing user from a group
        objGroup.PutEx 4, "member", Array(sUserPath)
       
        On Error Resume Next
        objGroup.SetInfo
        boolRC = (Err.Number <> 0)
        On Error GoTo 0

 
        'Error-handling
        If boolRC Then
            ClearUserGroups = False
            Exit Function
        End If
        
        Exit Do
    Loop

 
Next
   
ClearUserGroups = True

End Function


Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported
This work by Albert Gareev is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported.