1. 程式人生 > 其它 >查詢本地域及域帳號詳細資訊(包含所屬Group)

查詢本地域及域帳號詳細資訊(包含所屬Group)

查詢本地域及域帳號詳細資訊(包含所屬Group)

1、獲取當前域資訊

2、獲取當前登入的域帳號

3、使用域帳號查詢該域帳號的詳細資訊

4、查詢該域帳號所屬分組資訊(Group)

using System.DirectoryServices.AccountManagement;

class Program
    {
        static void Main(string[] args)
        {
            //獲取當前域 stringDomainName與stringDomainName的獲取方式都可可
            string stringDomainName = System.Environment.UserDomainName;
            //string stringDomainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;

            //獲取當前域帳號
            string userName = System.Environment.UserName;

            PrincipalContext PrincipalContext1 = new PrincipalContext(ContextType.Domain, stringDomainName);
            UserPrincipal UserPrincipal1 = new UserPrincipal(PrincipalContext1);
            
            //按域帳號查詢詳細資訊
            UserPrincipal1.SamAccountName = userName;
            PrincipalSearcher search = new PrincipalSearcher(UserPrincipal1);
            UserPrincipal user = search.FindOne() as UserPrincipal;
            Console.WriteLine($@"SamAccountName-{user.SamAccountName}, DisplayName-{user.DisplayName}, Name-{user.Name}, GivenName-{user.GivenName}, Surname-{user.Surname},
                Description-{user.Description}, Enabled-{user.Enabled}, LastLogon-{user.LastLogon}");
            
            //獲取所屬分組資訊
            PrincipalSearchResult<Principal> userGroups = user.GetGroups();
            foreach(var group in userGroups)
            {
                Console.WriteLine($"Group-{group.Name}");
            }
     }
}