2013-03-07 138 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(); 
相关问题