下面是一些示例代码,用于查找OU中的所有计算机对象。当我打印属性字段时,我得到System.__ComObject
的几个值,如lastLogon
,lastLogonTimestamp
,pwdLastSet
,uSNChanged
等。我认为这些都是某种类型的日期类型值。
如何从中获取日期值?我想要一个c#解决方案而不是像这样的powershell解决方案:https://sweeneyops.wordpress.com/2012/06/11/active-directory-timestamp-conversion-through-powershell/
谢谢
using (DirectoryEntry entry = new DirectoryEntry("LDAP://" + ou))
{
using (DirectorySearcher searcher = new DirectorySearcher(entry))
{
searcher.Filter = ("(objectClass=computer)");
searcher.SizeLimit = int.MaxValue;
searcher.PageSize = int.MaxValue;
foreach (SearchResult result in searcher.FindAll())
{
DirectoryEntry computer = result.GetDirectoryEntry();
foreach(string propName in computer.Properties.PropertyNames)
{
foreach(object value in computer.Properties[propName])
{
Console.WriteLine($"{propName}: {value}");
}
}
}
}
}
我知道对象内部有一个很长的内部,我可以使用DateTime.FromFileTime(longType)
来获取日期。
Already answered here:如果只需要这个接口,就不需要添加对COM类型库的引用。
要使用COM类型,您可以在自己的代码中定义接口:
[ComImport, Guid("9068270b-0939-11d1-8be1-00c04fd8d503"), InterfaceType(ComInterfaceType.InterfaceIsDual)]
internal interface IAdsLargeInteger
{
long HighPart
{
[SuppressUnmanagedCodeSecurity] get; [SuppressUnmanagedCodeSecurity] set;
}
long LowPart
{
[SuppressUnmanagedCodeSecurity] get; [SuppressUnmanagedCodeSecurity] set;
}
}
并以相同的方式使用它:
var largeInt = (IAdsLargeInteger)directoryEntry.Properties[propertyName].Value;
var datelong = (largeInt.HighPart << 32) + largeInt.LowPart;
var dateTime = DateTime.FromFileTimeUtc(datelong);
还有一篇很好的文章,解释how to interpret ADSI data
您需要做的是向“Active DS类型库”添加COM引用
然后,以下代码将使其中一个字段的日期时间超出,例如“pwdLastSet”
IADsLargeInteger largeInt = (IADsLargeInteger)computer.Properties["pwdLastSet"][0];
long datelong = (((long)largeInt.HighPart) << 32) + largeInt.LowPart;
DateTime pwSet = DateTime.FromFileTimeUtc(datelong);