Removing Active Directory User from Groups where Group Name Starts With

728 Views Asked by At

I'm having trouble trying to overcome an issue in VB.net. What I'd like to achieve is to remove one specific AD user from all groups where the name of the group starts with "Google"...

If I know the full name of the group, this is a straightforward affair and I can do the following:

Dim ctx As DirectoryServices.AccountManagement.PrincipalContext = New DirectoryServices.AccountManagement.PrincipalContext(DirectoryServices.AccountManagement.ContextType.Domain, "Company.co.uk")
Dim googleremove As DirectoryServices.AccountManagement.GroupPrincipal = DirectoryServices.AccountManagement.GroupPrincipal.FindByIdentity(ctx, "Google-Group1")
googleremove.Members.Remove(ctx, DirectoryServices.AccountManagement.IdentityType.SamAccountName, "UserID")
googleremove.Save()

But the issue is my application won't always know which specific group the user needs to be removed from. There are 28 different groups each with thousands of users where the group name starts with "Google-". Is there an efficient way to remove the user from all groups where the name of the group starts with "Google-" that won't slow things down horribly?

2

There are 2 best solutions below

0
MattOverton On BEST ANSWER

I worked it out! Here is how I managed for anyone else with my issue:

Dim ctx As DirectoryServices.AccountManagement.PrincipalContext = New DirectoryServices.AccountManagement.PrincipalContext(DirectoryServices.AccountManagement.ContextType.Domain, "MyCompany.co.uk")
Dim usr As DirectoryServices.AccountManagement.UserPrincipal = DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(ctx, "User ID")
Dim grp As DirectoryServices.AccountManagement.GroupPrincipal = New DirectoryServices.AccountManagement.GroupPrincipal(ctx)
grp.Name = "Google-*"
grp.Members.Contains(usr)
Dim srch As DirectoryServices.AccountManagement.PrincipalSearcher = New DirectoryServices.AccountManagement.PrincipalSearcher(grp)
For Each s As DirectoryServices.AccountManagement.GroupPrincipal In srch.FindAll()
    s.Members.Remove(ctx, DirectoryServices.AccountManagement.IdentityType.SamAccountName, "User ID")
    s.Save()
Next
0
Gabriel Luci On

You said you know how to get the MemberOf information. Do you would loop through that array to find groups that start with "Google".

But keep in mind that the MemberOf array is an array of distinguishedNames, so the group names are prefixed with "CN=". So you really need to do something like this:

For Each groupDn as String in memberOf
    If groupDn.StartsWith("CN=Google"))
        //remove user from this group
    End If
Next

I haven't used VB in a while, so that may not work as-is. But that's the idea.