Saturday, May 19, 2012

Automating the deletion of orphaned users' network folders with PowerShell

We have a process that deletes the network folders of a user as they leave the university, whether it be a student graduation/transferring or an employee leaving/being terminated. Generally speaking, this process is pretty well tuned, but occasionally hiccups do happen and sometimes folders are left behind for users that don't exist anymore. I wrote a little PowerShell script to handle that. It needs to be run as a user that has access to remove these folders as well as one that can read AD user objects (any domain user by default).




My users' home folders are laid out in \\server\share\first_letter\username 
My folder would be at \\folder\share\m\marra for example. If yours is different, you'll have to tweak the line that starts with $directories. It relies on the folders having the exact same name as the user's username, which is really quite common. It also makes use of -exclude, because there are a few directories on the top level that are for shared folders that I needed excluded for obvious reasons. If your share only contains the user's folders, then you can drop the -exclude switch.


Also, as with any script that uses rm, del, or remove-item, COMMENT IT OUT FIRST! Run it once with the output going to the console only. Dry runs are always important to do when you're running any script that you find on the Internet!

No comments:

Post a Comment