Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Active Directory Account Expiration with LDAP and C#

I am wanting to set a new users account to expire in 90 days from when it is created. Here is my code to create the user and set everything up. Everything works except for the last block where i am trying to set it to expire.

            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();

Any Suggestions on how to get his working?

Thanks

like image 559
Calvin Piche Avatar asked Mar 07 '13 21:03

Calvin Piche


2 Answers

See The Documentation about this field. You'll need to convert that to "ticks" --

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) will get you the correct and exact value.

You can check your work (manually) by getting the value from the above expression and executing:

w32tm.exe /ntte 130149277684873234

The results of the above command for me was

150635 17:42:48.4873234 - 6/5/2013 12:42:48 PM
like image 194
Gus Avatar answered Oct 20 '22 00:10

Gus


Or you could do:

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

This is a bit easier to deal with than messing with ticks and all that

like image 39
Ybot Avatar answered Oct 19 '22 22:10

Ybot