TIP: 2 Ways userAccountControl Is Easier In AD PowerShell

BackgrounduserAccountControl

Anyone who wants to write scripts for Active Directory will eventually run into the famous userAccountControl attribute.  Usually this comes up when you are searching for disabled accounts.  Actually this attribute is a bit flag for 22 different account settings!  You can find them clearly documented in KB305144.  In the GUI you find these settings represented by checkboxes in Active Directory Users and Computers (ADUC) (pictured right).

I’ve done my share of VBScripts over the last 10 years, and this always took more lines of code than I wanted to write.  In this example on the Hey Scripting Guy blog you can see it would take 14 lines of code to report on disabled accounts.  To make matters worse you had to understand LDAP bitwise filter syntax.  In an earlier post I demonstrated this syntax for querying AD based on a bit value.

The good news is that in Windows Server 2008 R2 and above we have two cmdlets that make this easy.

One Line Of PowerShell

With the Active Directory module for PowerShell and the Search-ADAccount cmdlet those 14 lines of VBScript turn into a single line:

PS C:\> Search-ADAccount -AccountDisabled

To limit the results to users or computers you can try one of these handy switches:

PS C:\> Search-ADAccount –AccountDisabled –UsersOnly

PS C:\> Search-ADAccount –AccountDisabled –ComputersOnly

The Search-ADAccount cmdlet has several switches that target the userAccountControl bit flags:

  • AccountDisabled
  • AccountExpired
  • AccountExpiring
  • LockedOut
  • PasswordExpired
  • PasswordNeverExpires
  • AccountInactive (not really UserAccountControl, but very handy!)

Now we don’t have to fuss with all of the fancy LDAP syntax.

But wait… there’s more!

The Set-ADAccountControl cmdlet gives us 12 switches to toggle these checkboxes via script:

  • AccountNotDelegated
  • AllowReversiblePasswordEncryption
  • CannotChangePassword
  • DoesNotRequirePreAuth
  • Enabled
  • HomedirRequired
  • MNSLogonAccount
  • PasswordNeverExpires
  • PasswordNotRequired
  • TrustedForDelegation
  • TrustedToAuthForDelegation
  • UseDESKeyOnly

Now you can turn the flags on and off like this:

PS C:\> Set-ADAccountControl JoeUser –PasswordNeverExpires $true

PS C:\> Set-ADAccountControl JoeUser –PasswordNeverExpires $false

Wow!  Now that was easy.

PS…

Closing reminders:

  • You’ll need the RSAT for Windows 7 or Windows 8 to get the cmdlets on your workstation.
  • Don’t forget to type Import-Module ActiveDirectory before trying these one-liners.
  • You can even run these against legacy 2003 or 2008 domain controllers using the guidance here.

Enjoy!