Adding group to local administrators

2019-07-31 16:20发布

问题:

I am trying to add an existing group in Local Administrators. The group "ABC\Some Active Group" exists. I can add that through Windows GUI but I need to add it through code. Here is what I have tried so far:

public static bool AddGroup(string machineName, string groupName)
{
    bool ifSuccessful = false;
    try
    {
        DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + machineName);
        DirectoryEntry admGroup = localMachine.Children.Find("administrators", "group");
        //admGroup.Children.Add(groupName, "Group"); 
        admGroup.Invoke("Add", groupName);
        admGroup.CommitChanges();

        ifSuccessful = true;

    }
    catch (Exception ex)
    {
        ifSuccessful = false;
        //logging
        Console.WriteLine(machineName + " ----------" + ex.Message);
    }
    return ifSuccessful;
}

and I am calling it like:

AddGroup(Environment.MachineName, @"ABC\Some Active Group");

I get the exception, (its an inner exception)

An invalid directory pathname was passed

I also tried adding it like:

admGroup.Children.Add(groupName, "Group");

But then I got the exception:

The Active Directory object located at the path WinNT://ABC/MachineName/Administrators is not a container

I have been able to successfully get all the users and groups with admGroup, I can't just add one. Can someone please tell me what am I doing wrong ?

回答1:

You need to call AddGroup like this

AddGroup(Environment.MachineName, "WinNT://" + Environment.MachineName + "/Some Active Group");