前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C#获取AD域中计算机和用户的信息

C#获取AD域中计算机和用户的信息

作者头像
用户1637609
发布2018-04-12 15:06:06
2.6K0
发布2018-04-12 15:06:06
举报
文章被收录于专栏:马洪彪

如果你的计算机加入了某个AD域,则可以获取该域中所有的计算机和用户的信息。

所用程序集,需要.Net Framework 4。

添加程序集引用 System.DirectoryServices.AccountManagement

获取AD域名称,未加入AD域的,只能获取计算机名称。

如果未加入任何域,则后续的获取域用户、计算机等操作将无法进行,实例化域上下文对象时,会抛出异常。

代码语言:javascript
复制
1 IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
2 string hostName = ipGlobalProperties.HostName;
3 string domainName = ipGlobalProperties.DomainName;

获取指定域中的用户的查找对象。

代码语言:javascript
复制
1 PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, domainName);
2 UserPrincipal userPrincipal = new UserPrincipal(principalContext);
3 PrincipalSearcher principalSearcher = new PrincipalSearcher(userPrincipal);

查找域中用户及其信息。

代码语言:javascript
复制
 1 StringBuilder sb = new StringBuilder(); 
 2 foreach (UserPrincipal userPrincipalSearchResult in principalSearcher.FindAll())
 3 {
 4     sb.AppendLine(string.Format("UPN:{0}", userPrincipalSearchResult.UserPrincipalName));
 5     sb.AppendLine(string.Format("姓氏Last Name:{0}", userPrincipalSearchResult.Surname));
 6     sb.AppendLine(string.Format("中间名:{0}", userPrincipalSearchResult.MiddleName));
 7     sb.AppendLine(string.Format("Given Name/First Name名:{0}", userPrincipalSearchResult.GivenName));
 8     sb.AppendLine(string.Format("名称:{0}", userPrincipalSearchResult.Name));
 9     sb.AppendLine(string.Format("上次登录时间:{0}", userPrincipalSearchResult.LastLogon));
10 }
11 userPrincipal.Dispose();
12 Console.WriteLine(sb.ToString());

查找域中计算机及其信息,类似于查找用户。首先使用域上下文对象实例化一个计算机对象,然后使用该对象实例化一个查找对象。

查找的结果,即为计算机对象,循环获取信息即可。

代码语言:javascript
复制
 1 ComputerPrincipal computerPrincipal = new ComputerPrincipal(principalContext);
 2 principalSearcher = new PrincipalSearcher(computerPrincipal);
 3 // 
 4 foreach (ComputerPrincipal computerPrincipalSearchResult in principalSearcher.FindAll())
 5 {
 6     sb.AppendLine(string.Format("UPN:{0}", computerPrincipalSearchResult.UserPrincipalName));
 7     sb.AppendLine(string.Format("描述:{0}", computerPrincipalSearchResult.Description));
 8     sb.AppendLine(string.Format("是否启用:{0}", computerPrincipalSearchResult.Enabled));
 9     sb.AppendLine(string.Format("SAM账号名:{0}", computerPrincipalSearchResult.SamAccountName));
10     sb.AppendLine(string.Format("名称:{0}", computerPrincipalSearchResult.Name));
11     sb.AppendLine(string.Format("上次登录时间:{0}", computerPrincipalSearchResult.LastLogon));
12 }
13 computerPrincipal.Dispose();
14 Console.WriteLine(sb.ToString());

参考链接:http://www.codeproject.com/Articles/489348/Active-Directory-Users-and-Computers

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2014-05-31 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档