Hinzufügen eines lokalen Benutzers zur lokalen Administratorgruppe

Ich schreibe ein C # -Programm, um es aus den Labs zu entfernen, in denen ich arbeite. Das Programm erstellt ein lokales Administratorkonto (itadmin), legt das Kennwort fest und legt fest, dass das Kennwort niemals abläuft, und fügt das Konto der lokalen Administratorgruppe hinzu. Das Programm erstellt das neue Benutzerkonto und legt alles korrekt fest, aber wenn es versucht, es der Administratorgruppe hinzuzufügen, erhalte ich eine sehr unscheinbare Ausnahme. Muss ich das Hinzufügen zur Gruppe überhaupt korrigieren? Was vermisse ich?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;

namespace CreateITAdmin
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string userName = "itadmin";
                string userPassword = "password";

                Console.WriteLine("Building System Information");
                DirectoryEntry localMachine = new DirectoryEntry("WinNT://.,computer");
                DirectoryEntry newUser = localMachine.Children.Add(userName, "user");
                DirectoryEntry admGroup = new DirectoryEntry("WinNT://./Administrators,group");

                Console.WriteLine("Building User Information");
                newUser.Properties["FullName"].Value = "IT Administrative User";
                newUser.Invoke("Put", new object[] { "UserFlags", 0x10000 });

                Console.WriteLine("Setting User Password");
                newUser.Invoke("SetPassword", new object[] { userPassword });

                newUser.CommitChanges();

                Console.WriteLine("Adding itadmin to Administrators Group");
                admGroup.Invoke("Add", "WinNT://./" + newUser);

                Console.WriteLine("Cleaning Up");
                localMachine.Close();
                newUser.Close();
                admGroup.Close();
            }
            catch (System.DirectoryServices.DirectoryServicesCOMException E)
            {
                Console.WriteLine(E.Message.ToString());
                Console.ReadLine();
            }
            catch (System.Runtime.InteropServices.COMException E)
            {
                Console.WriteLine(E.Message.ToString());
                Console.ReadLine();
            }
            catch (System.Reflection.TargetInvocationException E)
            {
                Console.WriteLine(E.Message.ToString());
                Console.ReadLine();
            }
            catch (Exception E)
            {
                Console.WriteLine(E.Message.ToString());
                Console.ReadLine();
            }

            Console.WriteLine();
            Console.WriteLine("Press Any Key to Continue");
            Console.ReadLine();
            return;
        }
    }
}

Die Code-Ausgabe ist unten:

Building System Information
Building User Information
Setting User Password
Adding itadmin to Administrators Group
Exception has been thrown by the target of an invocation.

Jede Einsicht wäre sehr zu schätzen.

UPDATE 1: Mit Hilfe von @ Grumbler85 werden die folgenden Ausnahmen aufgelistet:

System.Reflection.TargetInvocationException: Exception has been thrown by the target 
of an invocation. ---> System.Runtime.InteropServices.COMException: A member could not
be added to or removed from the local group because the member does not exist. --- End
of inner exception stacktrace --- at System.DirectoryServices.DirectoryEntry.Invoke
(String methodName,Object[]args) at CreateITAdmin.Program.Main(String[]args)in 
H:\code\CS\CreateITAdmin\CreateITAdmin\Program.cs:line 37

Auch mit Hilfe von @ Grumbler85 habe ich daran gearbeitet, die Bibliotheksnutzung auf System.DirectoryServices.AccountManagement zu aktualisieren. Es scheint viel einfacher und einfacher in der Anwendung zu sein. Weitere Updates / Details folgen, sobald ich Fortschritte mache.

Update 2: Ich weiß, dass dies eine schnelle Fortsetzung ist, aber ich konnte das Update auf den neuen Namespace abschließen. Nach einem kleinen Fehler beim Definieren des Computers konnte ich erfolgreich einen Benutzer erstellen, das Kennwort festlegen, das Kennwort so aktualisieren, dass es niemals abläuft, und den Benutzer der Administratorgruppe hinzufügen. Vielen Dank an @ Grumbler85 für das Update auf den neuen Namespace. Der neue Code ist unten:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

namespace CreateITAdmin
{
    class Program
    {
        static void Main(string[] args)
        {
            string userName = "itadmin";
            string userPassword = "IT-Engineering1";
            PrincipalContext systemContext = null;

            try
            {
                Console.WriteLine("Building System Information");
                systemContext = new PrincipalContext(ContextType.Machine, null);
            }
            catch (Exception E)
            {
                Console.WriteLine("Failed to create System Context.");
                Console.WriteLine("Exception: " + E);

                Console.WriteLine();
                Console.WriteLine("Press Any Key to Continue");
                Console.ReadLine();
                return;
            }

            //Check if user object already exists
            Console.WriteLine("Checking if User Exists.");
            UserPrincipal usr = UserPrincipal.FindByIdentity(systemContext, userName);
            if (usr != null)
            {
                Console.WriteLine(userName + " already exists. Exiting!!");
                Console.ReadLine();
                return;
            }

            //Create the new UserPrincipal object
            Console.WriteLine("Building User Information");
            UserPrincipal userPrincipal = new UserPrincipal(systemContext);
            userPrincipal.Name = userName;
            userPrincipal.DisplayName = "IT Administrative User";
            userPrincipal.PasswordNeverExpires = true;
            userPrincipal.SetPassword(userPassword);
            userPrincipal.Enabled = true;

            try
            {
                Console.WriteLine("Creating New User");
                userPrincipal.Save();
            }
            catch (Exception E)
            {
                Console.WriteLine("Failed to create user.");
                Console.WriteLine("Exception: " + E);

                Console.WriteLine();
                Console.WriteLine("Press Any Key to Continue");
                Console.ReadLine();
                return;
            }

            GroupPrincipal groupPrincipal = null;
            try
            {
                groupPrincipal = GroupPrincipal.FindByIdentity(systemContext, "Administrators");

                if (groupPrincipal != null)
                {
                    //check if user is a member
                    Console.WriteLine("Checking if itadmin is part of Administrators Group");
                    if (groupPrincipal.Members.Contains(systemContext, IdentityType.SamAccountName, userName))
                    {
                        Console.WriteLine("Administrators already contains " + userName);
                        return;
                    }
                    //Adding the user to the group
                    Console.WriteLine("Adding itadmin to Administrators Group");
                    groupPrincipal.Members.Add(userPrincipal);
                    groupPrincipal.Save();
                    return;
                }
                else
                {
                    Console.WriteLine("Could not find the group Administrators");
                }
            }
            catch (Exception E)
            {
                Console.WriteLine("Exception adding user to group.");
                Console.WriteLine("Exception: " + E);

                Console.WriteLine();
                Console.WriteLine("Press Any Key to Continue");
                Console.ReadLine();
            }

            Console.WriteLine("Cleaning Up");
            groupPrincipal.Dispose();
            userPrincipal.Dispose();
            systemContext.Dispose();

            Console.WriteLine();
            Console.WriteLine("Press Any Key to Continue");
            Console.ReadLine();
            return;
        }
    }
}

Antworten auf die Frage(2)

Ihre Antwort auf die Frage