Powershell command to delete subfolders without deleting the root


I’m having problems to create a PS command that allows me to delete several subfolders without deleting the roof folder.


C:\Test has many subfolders:

  • C:\Test\Item1
  • C:\Test\Item2
  • C:\Test\Item3

And the folders Item1, Item2 and Item3 have many subfolders and files.

I would like to create a PS that would allow me to delete all the empty subfolders inside Item1, Item2 and Item3 without deleting Item1, Item2 and Item3 folders. It is possible that any of the Item folders is empty, but I don’t want to delete them, just the empty content of each folder.

This is just an example, I have a have around 300 Item folders inside Test.

I usually would use this:

But this deletes the folder root folder (Item1, Item2 or Item3) if they are empty.

Thanks in advance.


So you are looking to delete All Items inside Empty Subfolders or all items in General?

This will delete all Folders or Items in General inside of the Directory “C:\abc\”

This will delete all Folders that dont have any items in them.

This will look inside “C:\abc\” Get all the children and delete all empty Directories inside the Children in your example this would be Item1,Item2,…

Just a quick and dirty bit of Code as I dont have much time, hope I could be of help.

EDIT: Here is what i came up with, its not as performant as I’d like but it gets the job done and is fairly quick, try it out for yourself it worked for me – even threw in a couple of comments and output to clarify what’s going on.


Powershell command to delete subfolders without deleting the root by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply