2013-08-14 15 views
5

Próbuję pobrać datę wygaśnięcia z konta.Trwa wygaśnięcie konta użytkownika z ActiveDirectory

Próbowałem

DirectoryEntry user = new DirectoryEntry(iMem); 

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

to nie działa, tylko daje mi błąd „określonych oddanych nie jest prawidłowy”.

Gdy używam

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

zwraca obiekt Com, które jestem w stanie odczytać.

Korzystanie Windows PowerShell, działa dobrze, nie rozumiem, dlaczego to przyzwyczajenie praca ...

jest to kod używam w powershell

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

Odpowiedz

10

Można użyć nazw System.DirectoryServices.AccountManagement do osiągnięcia to zadanie. Po uzyskaniu UserPrincipal z PrincipalContext można sprawdzić właściwość 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(); 
} 

Jeśli zrobić chcesz użyć DirectoryEntry, to zrobić:

//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; 
} 

Innym sposobem analizowania wartości accountExpires używa refleksji:

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); 
} 
Powiązane problemy