2013-08-14 83 views
5

アカウントから有効期限を取得しようとしています。私はそれが動作しませんActiveDirectoryからのユーザーアカウントの有効期限の取得

DirectoryEntry user = new DirectoryEntry(iMem); 

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

を試してみた

は、私だけ「指定されたキャストは有効ではありません」というエラーになります。

私は読み取ることができませんよCOMオブジェクトを返します

var AccountExpiration = user.Properties["accountExpires"]; 
を使用しています。窓のPowerShellを使用して

、正常に動作し、私はなぜこの文句を言わない仕事を得ることはありません...

これはあなたが達成するためにSystem.DirectoryServices.AccountManagement名前空間を使用することができますPowerShellで私が使用するコード

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

答えて

10

ですこの仕事。 PrincipalContextからUserPrincipalを取得したら、UserPrincipal.AccountExpirationDateのプロパティを調べることができます。あなたははDirectoryEntryを使用したいです場合

PrincipalContext context = new PrincipalContext(ContextType.Domain); 

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

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

、次の操作を行います。

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); 
} 
accountExpires値を解析する別の方法は、反射を
//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; 
} 

使用している

関連する問題