RSS
email

Automatically clean up orphaned user directories

We've had a huge problem where users were removed from Active Directory, but somehow the administrators neglected to remove the home folder for the user from the file servers. This left someone with the nasty task of cleaning up the mess.

This script will work through a directory of home folders and lookup the user in AD. This is assuming that the home folder and the user id are the same. If the user is not found, or the account is disabled, the folder will be renamed with a leading "orphan-" followed by the original name. The script requires a parameter, which is the path where the folders are located. e.g. "findorphans.ps1 c:\users" The script requires that the Quest Powershell Commandlets are installed, and they can be downloaded free, here.


param($target)
$folders=Get-ChildItem -Path $target | Where-Object {$_.Name -notlike "orphan*" -and ($_.PSISContainer)} | Select-Object name
foreach ($folder in $folders){
Write-Host ""
$userid=""
"PROCESSING FOLDER: {0} "   -f $folder.name
write-host "Searching for a possible owner..."
$user=Get-QADUser $folder.name
$useracc=$user.AccountIsDisabled
$userid=$user.samaccountname
$newid="orphan-" + $folder.name
$fullpath=$target + "\" + $folder.name
$fullpath
"Account Disabled: {0} "   -f $user.AccountIsDisabled

if ($userid.length -lt "0" -or $user.AccountIsDisabled -eq "True") {
Write-Host "No owner found or account disabled, orphan folder renamed to" $newid -ForegroundColor Red
rename-Item -Path $fullpath -NewName $newid
}
else {
Write-Host "Owner found" $user -ForegroundColor Green
}
}
Bookmark and Share

4 comments:

Aaron Perrault said...

this looks like it is something i could definetly use. One question, will it accept UNC paths? Can i run this from my desktop machine against my file server, or should it run directly on the file server?

thanks

app

Aaron Perrault said...

It does work against UNC paths, and it is a GREAT script. Will definetly have a place in my toolbox.

app

Jean Louw said...

Hey, thanks for the feedback, I am glad you can use it. Yes its designed to run from your admin workstation to drive mappings and UNC paths.

Also, I have made some updates to it, but I havent posted it yet, some folders where users have removed permissions cant be renamed, so the script attempts to take ownership and then rename the folder. Ill post a copy of that script for you on Monday.

Thanks again for the feedback!

Jean Louw said...

Aaron,

As promised, I have posted the updated script for you.

http://powershellneedfulthings.blogspot.com/2009/05/update-automatically-clean-up-orphaned.html

Enjoy!

Post a Comment

Note: Only a member of this blog may post a comment.