I'm writing an application in VB.Net which accepts an AD account input by the user and deprovisions and disables it automatically. As part of this, it strips all AD groups it can from the user.
Note that certain users may be members of groups that the person running the program does not have permission to modify, and that's OK for my requirements. These groups do not have a standard naming convention or format.
The following code removes the user from all groups they are a member of successfully, skipping any groups the person operating the program does not have permission to modify, but the catch is the program then appears to soft lock after attempting to remove a group it cannot (such as Domain Users)! What can I do to prevent this?
Dim ctx As DirectoryServices.AccountManagement.PrincipalContext = New DirectoryServices.AccountManagement.PrincipalContext(DirectoryServices.AccountManagement.ContextType.Domain, "net.mydomain.co.uk")
Dim user As DirectoryServices.AccountManagement.UserPrincipal = DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(ctx, tbxUsertoDeprovision.Text)
For Each group As DirectoryServices.AccountManagement.GroupPrincipal In user.GetGroups(ctx)
Try
group.Members.Remove(user)
group.Save()
group.Dispose()
Catch ex As Exception
Continue For
End Try
Next
If I insert a Message Box into the Catch as follows:
Catch ex As Exception
MessageBox.Show(ex.ToString())
Continue For
Then run the code, it displays the following message box, but only once:
System.InvalidOperation.Exception: The member can not be removed from the Group object's Members property because it has this group as its primary group. (This is at the group.Members.Remove(user)
line).
The program then goes no further and no code after Next
is ever executed. I'm forced to close the application.