← All writing

Tackling orphaned user folders: a PowerShell solution

Some IT problems don't come from anything breaking. They come from two normal processes not quite lining up. Orphaned user folders were one of those for us.

The problem

In our domain, user accounts are deleted after a period of inactivity, which is standard practice. But deleting the account left the user's folder behind in C:\Users.

When that person signed in again later, Windows didn't reuse the leftover folder. It created a new profile folder next to it, so the same user ended up with duplicate folders. On student laptops with 64 GB drives, that filled the disk quickly.

What you need

  • Intune Remediations (formerly Proactive Remediations), or any way to run a detection and remediation script as SYSTEM
  • The two scripts linked below, with the variables at the top adjusted for your organization

The solution

I wrote a detection script and a remediation script. Detection finds orphaned folders; remediation removes them. Deleting a folder whose owner no longer exists often runs into broken permissions, so the remediation tries several approaches, from simplest to most forceful.

See the scripts on GitHub

How the remediation works

  1. Set up. It sets its variables, creates its log and cleanup paths if they don't exist, and logs which accounts are on the device before it starts.
  2. Find orphans. It compares the folders in C:\Users with the user profiles registered in Windows. Any folder without a matching profile is orphaned. (The Public folder and its own cleanup folder are skipped.)
  3. Try a normal delete. It attempts to delete each orphaned folder.
  4. Fix permissions and try again. If that fails, it gives the SYSTEM account ownership and full control, then deletes the folder recursively, continuing past errors.
  5. Go file by file. If the folder is still there, it collects the remaining files into a list and fixes permissions on each one and deletes it individually, then does the same for the remaining subfolders.
  6. Move it out of the way. If anything still survives, it moves the folder into a cleanup directory, so C:\Users stays clean and the duplication doesn't keep happening.

The script works out whether it's running as SYSTEM or as a user and puts its log file in the right place, under an organization folder in ProgramData or AppData.

Results

This fixed our orphaned folder problem: student laptops no longer fill up with duplicate profile folders. It's a good example of how a little scripting can solve a problem that looks bigger than it is.

If you're seeing the same thing, feel free to use and modify the scripts. Happy scripting!