2013-03-07 52 views
4

我想將新用戶帳戶設置爲在創建後的90天內過期。這裏是我的代碼來創建用戶並設置一切。除了最後一塊我試圖將其設置爲過期的所有東西都可以工作。使用LDAP和C#設置Active Directory帳戶到期時間

  DirectoryEntry newUser = dirEntry.Children.Add("CN=" + cnUser, "user"); 
      newUser.Properties["samAccountName"].Value = cnUser; 
      newUser.Properties["userPrincipalName"].Value = cnUser; 
      newUser.Properties["pwdLastSet"].Value = 0; 
      newUser.CommitChanges(); 

      //Changes Password 
      String passwrd = userPassword.ToString(); 
      newUser.Invoke("SetPassword", new object[] { passwrd }); 
      newUser.CommitChanges(); 

      //Sets User Account to Change Passowrd on new login 
      newUser.Properties["pwdLastSet"].Value = 0; 
      newUser.CommitChanges(); 

      //Enables account 
      newUser.Properties["userAccountControl"].Value = (int)newUser.Properties["userAccountControl"].Value & ~0x2; 
      newUser.CommitChanges(); 

      //Set the account to expire in 90 days 
      var dt1 = DateTime.Today.AddDays(90); 
      newUser.Properties["accountExpires"].Value = dt1.ToFileTime().ToString(); 
      newUser.CommitChanges(); 

如何讓自己的工作有什麼建議?

感謝

回答

6

The Documentation這個領域。你需要將其轉換成「滴答」 -

the number of 100-nanosecond intervals since January 1, 1601 (UTC). A value of 0 or 0x7FFFFFFFFFFFFFFF (9223372036854775807) indicates that the account never expires. 

new DateTime(DateTime.UtcNow.AddDays(90).Ticks - new DateTime(1601, 1, 1).Ticks)將讓你正確和精確的數值。

您可以通過上述表達式得到的值並執行檢查你的工作(手動):

w32tm.exe /ntte 130149277684873234 

上述命令的結果對我來說是

150635 17:42:48.4873234 - 6/5/2013 12:42:48 PM 
+0

日期時間的蜱計數從1月蜱0001它需要標準化來算蜱開始1月1日1601 – 2013-03-07 21:47:14

+0

的DateTime.Today.Add(90).Ticks給正確的日期可以達到月份和日期,但是在一年中它已經設置爲3613,基本上在滴答開始的地方增加了1600。 – 2013-03-07 21:58:23

+0

好吧,所以減去'新日期時間(1600,1,1).Ticks'應該修復它。更新的答案即將推出 – Gus 2013-03-07 22:12:01

3

或者你可以做:

DateTime expire = System.DateTime.Now.AddDays(90); 
newUser.Properties["accountExpires"].Value = Convert.ToString((Int64)expire.ToFileTime()); 
newUser.CommitChanges(); 

這比處理ticks和所有那些更容易處理

0

參考:https://msdn.microsoft.com/en-us/library/ms180914(v=vs.80).aspx

//Use the DirectoryEntry.InvokeSet method to invoke the AccountExpirationDate property setter. 

System.DirectoryServices.DirectoryEntry dirEntryLocalMachine = 
    new System.DirectoryServices.DirectoryEntry("WinNT://" + Environment.MachineName + "/" + userID); 

dirEntryLocalMachine .InvokeSet("AccountExpirationDate", new object[] {new DateTime(2005, 12, 29)}); 

//Commit the changes. 
usr.CommitChanges(); 
相關問題