OU 时间戳 ComObject

OU timestamp ComObject

这是我的一些示例代码,用于查找 OU 中的所有计算机对象。当我打印出 属性 字段时,我得到了几个值的 System.__ComObject,例如 lastLogonlastLogonTimestamppwdLastSetuSNChanged等。我假设这些都是某种日期类型的值。

如何从中获取日期值?我想要一个 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) 从中获取日期。

您需要做的是添加对 "Active DS Type Library"

的 COM 引用

然后下面的代码将从其中一个字段中生成一个日期时间,例如 "pwdLastSet"

IADsLargeInteger largeInt = (IADsLargeInteger)computer.Properties["pwdLastSet"][0];
long datelong = (((long)largeInt.HighPart) << 32) + largeInt.LowPart;
DateTime pwSet = DateTime.FromFileTimeUtc(datelong);

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