C#操作AD域中计算机

记录下如何操作域中的计算机:

 /// <summary>
        /// 根据pc名称删除
       /// </summary>
        public bool PcDelete(string pcName,string username,string password)
        {
            try
            {
                //IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
                //string doname = ipGlobalProperties.DomainName;
                // PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, doname);
                PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, serveraddress, username, password);//serveraddress不要加ladp 直接写IP地址就可以了
                ComputerPrincipal computerPrincipal = ComputerPrincipal.FindByIdentity(principalContext, IdentityType.Name, pcName);
                computerPrincipal.Delete();//删除计算机
                computerPrincipal.Dispose();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// pc禁用
        /// </summary>
        public bool PcUnEnabled(string pcName, string username, string password)
        {
            try
            {
                //IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
                //string doname = ipGlobalProperties.DomainName;
                // PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, doname);
                PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, serveraddress, username, password);
                ComputerPrincipal computerPrincipal = ComputerPrincipal.FindByIdentity(principalContext, IdentityType.Name, pcName);
                computerPrincipal.Enabled = false;//禁用计算机
                computerPrincipal.Save();
                computerPrincipal.Dispose();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

查询pc

 /// <summary>
        /// 根据Pc名称获取pc
        /// </summary>
        /// <param name="pcName"></param>
        /// <returns></returns>
        public ComputerPrincipal GetPcByName(string pcName, string username, string password)
        {
            try
            {
                //IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
                //string doname = ipGlobalProperties.DomainName;
                // PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, doname);
                PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, serveraddress, username, password);
                ComputerPrincipal computerPrincipal = ComputerPrincipal.FindByIdentity(principalContext, IdentityType.Name, pcName);
                return computerPrincipal;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 根据sid获取Pc
        /// </summary>
        /// <param name="sid"></param>
        /// <returns></returns>
        public ComputerPrincipal GetPcBySid(string sid, string username, string password)
        {
            try
            {
                //IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
                //string doname = ipGlobalProperties.DomainName;
                // PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, doname);
                PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, serveraddress, username, password);
                ComputerPrincipal computerPrincipal = ComputerPrincipal.FindByIdentity(principalContext, IdentityType.Sid, sid);
                return computerPrincipal;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

根据SID查询时,sid读出来为一个byte[]类型,需要一个转换算法后才可以使用,下面附一个转换过程:

 #region sid转换
        private string ConvertByteToStringSid(Byte[] sidBytes)
        {
            StringBuilder strSid = new StringBuilder();
            strSid.Append("S-");
            try
            {
                // Add SID revision.
                strSid.Append(sidBytes[0].ToString());
                // Next six bytes are SID authority value.
                if (sidBytes[6] != 0 || sidBytes[5] != 0)
                {
                    string strAuth = String.Format
                        ("0x{0:2x}{1:2x}{2:2x}{3:2x}{4:2x}{5:2x}",
                        (Int16)sidBytes[1],
                        (Int16)sidBytes[2],
                        (Int16)sidBytes[3],
                        (Int16)sidBytes[4],
                        (Int16)sidBytes[5],
                        (Int16)sidBytes[6]);
                    strSid.Append("-");
                    strSid.Append(strAuth);
                }
                else
                {
                    Int64 iVal = (Int32)(sidBytes[1]) +
                        (Int32)(sidBytes[2] << 8) +
                        (Int32)(sidBytes[3] << 16) +
                        (Int32)(sidBytes[4] << 24);
                    strSid.Append("-");
                    strSid.Append(iVal.ToString());
                }

                // Get sub authority count...
                int iSubCount = Convert.ToInt32(sidBytes[7]);
                int idxAuth = 0;
                for (int i = 0; i < iSubCount; i++)
                {
                    idxAuth = 8 + i * 4;
                    UInt32 iSubAuth = BitConverter.ToUInt32(sidBytes, idxAuth);
                    strSid.Append("-");
                    strSid.Append(iSubAuth.ToString());
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.Write(ex.Message);
                return "";
            }
            return strSid.ToString();
        }
        #endregion
DirectoryEntry 移动到指定OU
 #region  移动目录
         public DirectoryEntry MoveComputer(string category, string name)
        {
            DirectoryEntry de = null;
            DirectorySearcher ds = null;
            DirectoryEntry userEntry = null;
            try
            {
                de = new DirectoryEntry(GetDomainPath(), adminUser, adminPwd, AuthenticationTypes.Secure);
                ds = new DirectorySearcher(de);
                string queryFilter = string.Format("(&(objectCategory=" + category + ")(sAMAccountName={0}))", name);
                ds.Filter = queryFilter;
                ds.Sort.PropertyName = "cn";
                SearchResult sr = ds.FindOne();
                if (sr != null)
                {
                    userEntry = sr.GetDirectoryEntry();
                    DirectoryEntry dp = new DirectoryEntry("LDAP://192.168.0.1/OU=test,DC=test,DC=com", adminUser, adminPwd);
                    userEntry.MoveTo(dp);
                }
                return userEntry;
            }
            catch (Exception ex)
            {
                return new DirectoryEntry();
            }
            finally
            {
                if (ds != null)
                {
                    ds.Dispose();
                }
                if (de != null)
                {
                    de.Dispose();
                }
            }
        }
        #endregion