Friday, September 9, 2011

Disable or enable an Active Directory account on a schedule

I know Active Directory has log on hours and account expiration, but what if you need to disable a user account at a specific time? I found this can be useful when an employee quits or is terminated because as long as I know in advance, I can schedule their account to be disabled and don't have to remember to do it manually. The trick is to use AD command line tools that are available on Windows Server through a batch file so it can be scheduled to run at a certain time. Here's how it can be done:

  1. Create a new text file and rename it to something.bat. This is the start of your batch script file that you'll schedule later on.
  2. Right-click your .bat file and select Edit. This should open the file in notepad so you can enter your command
  3. Enter dsmod user USER_DN -disabled (yes|no) into your batch file. To expand on what this means:
    1. dsmod user is required. This uses the directory services modify program built into your server,a and also says it will be a user change.
    2. USER_DN represents the DN of the user you want to disable within your Active Directory structure. Say your Active Directory domain is, your user is named Test User, and the user exists in the OU named DomUsers. Your USER_DN value would be CN=Test User,OU=DomUsers,DC=domain,DC=com
    3. -disabled is required because it defines which property for the user that you are changing
    4. (yes|no) means to select yes or no, whichever one you want to set disabled equal to
  4. Save your batch file
  5. Use Windows Scheduled Tasks to schedule the file. You can browse out and select it, then pick the schedule you want it to run.
Here are two basic examples of the command using the information above

To disable Test User the command is

dsmod user "CN=Test User,OU=DomUsers,DC=domain,DC=com" -disabled yes

And to enable Test User

dsmod user "CN=Test User,OU=DomUsers,DC=domain,DC=com" -disabled no

Notice that I put the USER_DN in quotes. This is because there are spaces. You're best off using quotes around the USER_DN regardless since it will work with the quotes regardless or spaces.

Also, if your user is buried in multiple OUs, just add them to the DN. If Test User had been in three tiers of OUs, such as a top-level named USA, a mid-level named MN, and a bottom-level named DomUsers, the USER_DN value would be CN=Test User,OU=DomUsers,OU=MN,OU=USA,DC=domain,DC=com

To see the Microsoft KB article outlining doing this with dsmod, click here