vb.netactive-directorydirectoryservicesaccount-management

Removing Active Directory User from Groups where Group Name Starts With


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?


Solution

  • 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