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
}
}

4 thoughts on “Automatically clean up orphaned user directories”

  1. 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

  2. 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!

Comments are closed.