2013-08-14 24 views
5

Tôi đang cố truy xuất ngày hết hạn từ tài khoản.Truy xuất hết hạn tài khoản người dùng từ ActiveDirectory

Tôi đã thử

DirectoryEntry user = new DirectoryEntry(iMem); 

var AccountExpiration = DateTime.FromFileTime((int)user.Properties["accountExpires"].Value); 

nó không hoạt động, chỉ mang lại cho tôi những lỗi "dàn diễn viên được chỉ định không hợp lệ".

Khi tôi sử dụng

var AccountExpiration = user.Properties["accountExpires"]; 

trả về một đối tượng com, mà tôi không thể đọc được.

sử dụng Windows PowerShell, hoạt động tốt, tôi không hiểu tại sao công việc này wont ...

đây là đoạn code tôi sử dụng trong PowerShell

$Expires = [datetime]::FromFileTime($tmpUser.accountExpires) 

Trả lời

10

Bạn có thể sử dụng không gian tên System.DirectoryServices.AccountManagement để hoàn thành nhiệm vụ này. Khi bạn nhận được số UserPrincipal từ số PrincipalContext, bạn có thể kiểm tra thuộc tính UserPrincipal.AccountExpirationDate.

PrincipalContext context = new PrincipalContext(ContextType.Domain); 

UserPrincipal p = UserPrincipal.FindByIdentity(context, "Domain\\User Name"); 

if (p.AccountExpirationDate.HasValue) 
{ 
    DateTime expiration = p.AccountExpirationDate.Value.ToLocalTime(); 
} 

Nếu bạn làm muốn sử dụng DirectoryEntry, làm điều này:

//assume 'user' is DirectoryEntry representing user to check 
DateTime expires = DateTime.FromFileTime(GetInt64(user, "accountExpires")); 

private Int64 GetInt64(DirectoryEntry entry, string attr) 
{ 
    //we will use the marshaling behavior of the searcher 
    DirectorySearcher ds = new DirectorySearcher(
    entry, 
    String.Format("({0}=*)", attr), 
    new string[] { attr }, 
    SearchScope.Base 
    ); 

    SearchResult sr = ds.FindOne(); 

    if (sr != null) 
    { 
     if (sr.Properties.Contains(attr)) 
     { 
      return (Int64)sr.Properties[attr][0]; 
     } 
    } 

    return -1; 
} 

Một cách khác để phân tích giá trị accountExpires đang sử dụng phản ánh:

private static long ConvertLargeIntegerToLong(object largeInteger) 
{ 
    Type type = largeInteger.GetType(); 

    int highPart = (int)type.InvokeMember("HighPart", BindingFlags.GetProperty, null, largeInteger, null); 
    int lowPart = (int)type.InvokeMember("LowPart", BindingFlags.GetProperty | BindingFlags.Public, null, largeInteger, null); 

    return (long)highPart <<32 | (uint)lowPart; 
} 

object accountExpires = DirectoryEntryHelper.GetAdObjectProperty(directoryEntry, "accountExpires"); 
var asLong = ConvertLargeIntegerToLong(accountExpires); 

if (asLong == long.MaxValue || asLong <= 0 || DateTime.MaxValue.ToFileTime() <= asLong) 
{ 
    return DateTime.MaxValue; 
} 
else 
{ 
    return DateTime.FromFileTimeUtc(asLong); 
}