Freigeben über


Assign Computers to the User Account

The user principal for the new employee is retrieved in the following code example. For each computer specified, the employee is granted permission on the ComputerPrincipal object.

For more information, see the Find the Computers for this User Account and Grant User Permissions on the Computer topics.

        internal static bool AssignComputersToUser(string[] computers, string user)
        {
            // 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();
            }

            try
            {
                UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, user);
                foreach (string computer in computers)
                {
                    ComputerPrincipal computerPrincipal = FindTheComputer(computer);
                    if (computerPrincipal == null)
                    {
                        MessageBox.Show("Could not find Computer: " + computer);
                        return false;
                    }
                    GrantUserPermissionsOnComputerObject(userPrincipal, computerPrincipal);
                }
                return true;

            }
            catch (Exception e)
            {
                MessageBox.Show("Exception assigning computers to user. " + e);
                return false;
            }
        }

See Also

Reference

System.DirectoryServices.AccountManagement

Concepts

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

Send comments about this topic to Microsoft.

Copyright © 2008 by Microsoft Corporation. All rights reserved.