I have a PowerShell script. It is to remove the user from the Administrators group. It's working fine for local and domain users both.
Remove-LocalGroupMember -Group "Administrators" -Member "Admin02"
I want to implement this in C#. I have tried the below code. But it's not working for the domain account.
using (PrincipalContext ctx = new PrincipalContext(ContextType.Machine))
{
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.Name, args[0]);
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, "Administrators");
if (user != null && group != null)
{
try
{
if (group.Members.Remove(user))
{
Console.WriteLine("User successfully removed from Local Administrators.");
}
else
{
Console.WriteLine("User is not a Local Administrator1.");
}
}
catch (Exception ex)
{
Console.WriteLine("User is not a Local Administrator.");
Console.WriteLine(ex.ToString());
}
}
else
{
Console.WriteLine("User was not found.");
}
}
Its printing User was not found.
I have tried with ContextType.Domain
as well.
Edit: Thank you @Gabriel Luci. for providing the solution. I tried his solution, but there is a challenge with it.
I have a domain user name T1/spreda (forward slash).
But when I run your code and see the value of member, it shows users like this (with back slash). I have written this code to check the user.
var group = new DirectoryEntry("WinNT://./Administrators");
foreach (var m in (IEnumerable)group.Invoke("Members"))
{
var member = new DirectoryEntry(m);
var str = JsonConvert.SerializeObject(member);
Console.WriteLine(str);
//if (str.Contains(args[0]))
//{
// Console.WriteLine("Found");
// var returnVal = group.Invoke("Remove", new[] { member.Path });
// Console.WriteLine(returnVal.ToString());
// break;
So Is there a way to handle this?