Create a New Computer

Creating a new computer is a very straightforward process. There is only one problematic step: for the computer account to be usable, the programmer must include a $ sign at the end of the computer samAccountName

There are two ways to perform this task. The first is merely to call the ComputerPrincipal constructor with the computer's samAccountName, a password, and a boolean true value that specifies that the computer is enabled:

internal static bool CreateComputer(string computerSamAccountName, string computerPassword)
{
            // Creating the PrincipalContext
            PrincipalContext principalContext = null;            
            try
            {
                principalContext = new PrincipalContext(ContextType.Domain, "fabrikam", "DC=fabrikam,DC=com");
            }
            catch (Exception e)
            {
                MessageBox.Show("Failed to create PrincipalContext. Exception: " + e);
                Application.Exit();
            }

            // Create the computer
            // remember that computerSamAccountName must look like
            // "computerName$" for the account to be usable.
            ComputerPrincipal myComputer = new ComputerPrincipal(principalContext, computerSamAccountName,computerName), computerPassword, true);
            myComputer.Save();
}

Alternatively, you can also create an empty ComputerPrincipal object, given only the context, and use the displayName to generate a samAccountName. Then populate the appropriate properties of the ComputerPrincipal object and save it:

internal static bool CreateComputer(string displayName)
{
            // Creating the PrincipalContext
            PrincipalContext principalContext = null;            
            try
            {
                principalContext = new PrincipalContext(ContextType.Domain, "fabrikam", "DC=fabrikam,DC=com");
            }
            catch (Exception e)
            {
                MessageBox.Show("Failed to create PrincipalContext. Exception: " + e);
                Application.Exit();
            }

            // Create the computer
            ComputerPrincipal myComputer = new ComputerPrincipal(principalContext);
            CString randomPassword = GenerateARandomStrongPassword();

            myComputer.DisplayName = displayName;
            myComputer.SamAccountName = displayName + "$";
            myComputer.Enabled = true;
            myComputer.SetPassword(randomPassword);

            myComputer.Save();

}

See Also

Reference

System.DirectoryServices.AccountManagement
ComputerPrincipal

Concepts

About System.DirectoryServices.AccountManagement
Using System.DirectoryServices.AccountManagement

Send comments about this topic to Microsoft.

Copyright © 2008 by Microsoft Corporation. All rights reserved.