且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取AD里面指定OU或Container里面的计算机以及Lastlogon时间格式转换

更新时间:2022-09-09 10:01:25

至于什么是活动目录,大家可以去这里了解

.NET读取Active Directory(活动目录)里面的User和Computer信息主要用到了System.DirectoryServices命名空间里面的对象。

这里我主要用到了两个对象DirectoryEntryDirectorySearch

获取AD里面指定OU或Container里面的计算机以及Lastlogon时间格式转换
 1 //额外添加的命名空间
2 using System.DirectoryServices.ActiveDirectory;
3 using ActiveDs;
4
5 //ADComputerModel是自定义的实体对象
6 class Test
7 {
8 public List<ADComputerModel> GetComputer()
9 {
10 List<ADComputerModel> list = new List<ADComputerModel>();
11 DirectoryEntry deRoot = new DirectoryEntry();
12 deRoot.Username = "zhangxuefei";
13 deRoot.Password = "不告诉你";
14 deRoot.Path = "LDAP://域名/OU=**,DC=**,DC=**";
15 DirectorySearcher search = new DirectorySearcher();
16 search.SearchRoot = deRoot;
17 search.Filter = ("(objectClass=computer)");
18 DateTime? tmp = null;
19 foreach (SearchResult resEnt in search.FindAll())
20 {
21 var flag = resEnt.GetDirectoryEntry().Properties["Lastlogon"].Value;//获取最后登录时间
22
23 if (flag == null)
24 {
25 tmp = null;//这里也是Lastlogon当我们在AD里面创建一个计算机的时候什么都不设置的情况下的空值处理
26 }
27 else
28 {
29 //这里执行对Lastlogon时间格式的转换(因为Lastlogon的时间格式不是标准的时间格式需要转换)
30 //转换方法是在国外的网站上面查到的,需要引入Interop.ActiveDs.dll这个Com组件。实现的原理在这
31 LargeInteger largeInt = (LargeInteger)resEnt.GetDirectoryEntry().Properties["Lastlogon"][0];
32 Int64 liTicks = largeInt.HighPart * 0x100000000 + largeInt.LowPart;
33 if (liTicks == 0)
34 {
35 tmp = null;//这里也是Lastlogon在我们创建一个计算机的时候什么都不设置的情况下的空值处理
36 }
37 else if (DateTime.MaxValue.Ticks >= liTicks && DateTime.MinValue.Ticks <= liTicks)
38 {
39 tmp = DateTime.FromFileTime(liTicks);
40 }
41 }
42 list.Add(new ADComputerModel
43 {
44 ComputerName = resEnt.GetDirectoryEntry().Properties["CN"].Value.ToString(),//获取计算机名称
45 OSVersion = resEnt.GetDirectoryEntry().Properties["operatingsystem"].Value == null ? ""
: resEnt.GetDirectoryEntry().Properties["operatingsystem"].Value.ToString(),//获取操作系统名称
46 CreateTime = Convert.ToDateTime(resEnt.GetDirectoryEntry().Properties["whencreated"].Value),//获取创建时间
47 LastLoginTime = tmp//最后登录时间
48 //...可以根据自己的需要取不同的属性值
49 });
50 }
51 }
52
53 }
54
55 public class ADComputerModel
56 {
57 ///<summary>
58 /// 计算机名
59 ///</summary>
60 public string ComputerName { get; set; }
61
62 ///<summary>
63 /// 创建日期
64 ///</summary>
65 public DateTime? CreateTime { get; set; }
66
67 ///<summary>
68 /// 操作系统版本
69 ///</summary>
70 public string OSVersion { get; set; }
71
72 ///<summary>
73 /// 最后登录时间
74 ///</summary>
75 public DateTime? LastLoginTime { get; set; }
76 }
获取AD里面指定OU或Container里面的计算机以及Lastlogon时间格式转换

明天就是六"1"节了,祝各各单们节日愉快!

本文转自Rt-张雪飞博客园博客,原文链接http://www.cnblogs.com/mszhangxuefei/archive/2011/11/10/worknotes_3.html如需转载请自行联系原作者


张雪飞