Pete Hinchley: Disable User Accounts and Set Random Passwords on a Schedule using Powershell

This is just a quick tip demonstrating how you can easily disable one or more Active Directory user accounts, and randomise the password of each, using a single PowerShell command. I use this command as the action of a scheduled task to automatically reset several generic user accounts every Friday evening. The accounts may have been handed out to staff for short term requirements during the week, and the scheduled task ensures the accounts don't remain active longer than intended.

The code uses an LDAP filter to find all user accounts with a username that begins with either Generic or Test. It then disables and assigns a random 32 character password to each account (using characters with ASCII codes from 33 to 126).

powershell.exe -command "& { $filter = '(|(samaccountname=Generic*)(samaccountname=Test*))'; get-aduser -ldapfilter $filter | disable-adaccount -passthru | set-adaccountpassword -reset -newpassword (convertto-securestring -asplaintext (-join ((33..126) | get-random -count 32 | % {[char]$_})) -force) }"

Note: This code must be run on a computer where the Active Directory PowerShell cmdlets are installed.