I'm creating a program that adds and removes domain users to/from local groups on a specific computer.
I successfully finished part that adds users to group, but when it comes to removing I'm getting this error.
Exception thrown: 'System.DirectoryServices.AccountManagement.NoMatchingPrincipalException' in System.DirectoryServices.AccountManagement.dll An unhandled exception of type 'System.DirectoryServices.AccountManagement.NoMatchingPrincipalException' occurred in System.DirectoryServices.AccountManagement.dll Additional information: No security object matching the specified parameters found
Here is my function and example of what variables can contain
string username = "USER123"
string localGroupName = "Administrators"
string computername = "computer1"
using (PrincipalContext pc = new PrincipalContext(ContextType.Machine,computername))
{
GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, localGroupName);
group.Members.Remove(pc, IdentityType.Name, username);
group.Save();
}
I also tried to change IdentityType, but got same result
group.Members.Remove(pc, IdentityType.SamAccountName, username);
I can print all members of any group using foreach so I presume everything up to a "GroupPrincipal" is correct.
It seems like I'm putting in wrong username, but the username is correct (I'm using it to logon into a computer that is in domain) and using bellow formula did not help either.
DomainName\UserName
Also I found this thread, but to me it seems like almost the same thing, but written differently.
Any help or ideas is greatly appreciated! Sorry if I'm missing something obvious, but I'm using C# only for a while.
Found a solution for my problem. Maybe it can help to someone so I'm posting it here.
string computername = "computer1"
string groupName = "Administrators"
string usernameToRemove = "testUser"
using (PrincipalContext pc = new PrincipalContext(ContextType.Machine, computername))
using (GroupPrincipal localGroup = GroupPrincipal.FindByIdentity(pc, IdentityType.Name, groupname))
foreach (Principal groupUser in localGroup.GetMembers())
if (groupUser.SamAccountName == usernameToRemove)
{
localGroup.Members.Remove(groupUser);
localGroup.Save();
}
More or less I edited answer to this question. His solution is does not search through all members of a group as mine(if I undestand his code correctly), but working solution is working solution.