Disable all users in an AD Group

At my work, we had a unique and “sPeCiAL” requirement to disable all vendor VPN accounts on a daily basis. The premise was to allow vendors to login and work on projects and tickets, but only for a short period of time. They’d reach out to us, ask to enable their account so they could work on a specific ticket, then we’d oblige and re-enable their account so they could login and work. Management didn’t want them in there for longer than necessary though.

We used to use an old vbscript that would disable all accounts in a particular OU and we had all the accounts in the one “vendor-VPN” OU. This was great, except for when we received a new requirement to allow just a few accounts to be enabled all the time. I suggested to simply move the accounts that are to be enabled all the time to a different OU, but no, they wanted all the vendor accounts in the same place. Ugh… fine.

I looked around trying to find something that would accomplish this, and I wanted it to be PowerShell instead of VB, and I wanted it to be easy to modify the members that get disabled and ones that don’t. I’m not great at scripting so it took me a couple hours, but finally ended up with this two-line script that seems to work pretty well. We have it running as a scheduled task as a service account that has domain admin rights.

The script is as follows:
Get-ADGroupMember -Identity "Auto-Disable" | Get-ADUser -Property UserPrincipalName | select DistinguishedName > C:\software\users.txt

The above line basically goes and finds the Distinguished Name of all of the accounts that are in the “Auto-Disable” security group. Then, it dumps them into a text file called “users.txt” at C:\Software on the server where it is run from.

The second line of the script is:

Get-Content C:\software\users.txt | % { Set-ADUser $_ -Enabled:$false }

That line loads up the text file, reads through it and picks up all the Distinguished Names that are listed in it, and sets their account status to disabled. Now, if you run this manually in a powershell window, you’ll see a bunch of errors, but those can be ignored. They show up because there’s a bunch of other text in the file that gets created when you run the first line. With that aside, the accounts that are in the group get disabled perfectly.

Just posting this out there in case someone else has a reason to do this and can’t figure out how. You just need to create a group and add your accounts into it, then set a scheduled task on a server that calls this PowerShell whenever you want it to run.


Posted

in

by

Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.