Windows: how to delete repeating “infinite” nested folder structure

This can happen with a lot of different programs, or even with messing up a script or something: some loop happened at some point when copying/creating files on a disk, and you get a repeated folder structure clogging your storage.

I’ve had the issue with Robocopy, a vintage (1996!) .exe perfect for scripted simple file backups. Hey, the latest release is from 2019 after all 🙂

I used it to copy some user’s AppData in Windows 10, to another disk. The process took ages, which seemed weird to begin with, as the user’s AppData was about a few GB’s.

The command with parameters I used was the following:

The command ran for more than an hour, and then seemed to be stopped. Yeah, the mentioned F:\ disk was 100% full.

The result was pretty amazing. I solved the issue since I’ve had it so the screenshot below is made-up, but this is kinda faithful to the situation I had on the backup drive ( F: )

So the folder “Username” was containing its usual “Local”, “LocalLow” an “Roaming” directories, plus their orresponding files. But inside the “Local” directory, you have the whole AppData with its three sub-folders and all files again, recursively, and bearing the full name “Application Data”.
I think it went to about ~20 levels of depth, until the disk was full. I don’t understand how this happened, probably some bug with Robocopy unable to process the users directories correctly in Windows 10.

I wanted to delete the root folder “Username” to clean all that crap, and it was plainly impossible: Windows was getting lost in the depth, with long files, and ACLs (maybe that /copyall option on Robocopy wasn’t such a good idea to begin with…)

I had to use two tricks:

First trick is to take ownership of the whole content of the folder, as far as the command could go:

To be executed in elevated cmd, and ensure your user is among the administrators of course. If needed, check the parameters of takeown.exe and adapt to your needs with your specific user.

Second one is courtesy of Blackbam’s (1), and is a pretty ingenious little batch file (in elevated cmd/PS as well):

So you rename your first looping sub-directory to “x”, you move the content of x’s subdir to the root (including the looping directory within), and delete x as well as its content. If you have a humongous depth level, you can even loop that into some PowerShell or batch if you remember that 😉

I had a little issue with rd unable to delete some long filename within a “Microsoft” directory, but once takeown had done its job and the folder moved to a higher level, the Windows Explorer was enough to perform the deletion… some tedious manual job but I hadn’t that many depth levels in the end..

And that’s it, I managed to free all the space eaten by this annoying situation.

Morality: don’t use Robocopy to backup user’s AppData! 🙂

Sources: