Using C#, how do you check if a computer account is disabled in active directory?

后端 未结 8 884
暖寄归人
暖寄归人 2020-12-16 17:24

How do you check if a computer account is disabled in Active Directory using C#/.NET

8条回答
  •  暖寄归人
    2020-12-16 18:04

    Try this:

    class Program
    {
        static void Main(string[] args)
        {
            const string ldap = "LDAP://your-ldap-server-here";
    
            using (DirectoryEntry conn = new DirectoryEntry(ldap))
            {
                using (DirectorySearcher searcher = new DirectorySearcher(conn))
                {
                    searcher.Filter = "(|(samAccountName=userA)(samAccountName=userB))";
                    searcher.PropertiesToLoad.Add("samAccountName");
                    searcher.PropertiesToLoad.Add("userAccountControl");
    
                    using (SearchResultCollection results = searcher.FindAll())
                    {
                        foreach (SearchResult result in results)
                        {
                            int userAccountControl = Convert.ToInt32(result.Properties["userAccountControl"][0]);
                            string samAccountName = Convert.ToString(result.Properties["samAccountName"][0]);
                            bool disabled = ((userAccountControl & 2) > 0);
    
                            Console.WriteLine("{0} ({1:x}) :: {2}", samAccountName, userAccountControl, disabled);
                        }
                    }
                }
            }
    
            Console.ReadLine();
        }
    }
    

    The second bit of userAccountControl will be 1 if the account is disabled.

提交回复
热议问题