I am by no means a PowerShell{{1}} power user but occasionally I tinker when I have a need. Recently I was doing some cleanup of my audio directories and spent some time finding and removing duplicates MP3s.  After doing so, the thought occurred that I may now have numerous empty directories that ought to be cleaned up.  So I set out to find a quick PowerShell script to do the job.  After a few minutes of searching I didn’t find anything that did exactly what I wanted.  I did find an old article that showed how to do in in a batch file{{2}}.  But I don’t like running scripts that delete stuff from my computer if I don’t understand every little switch and command (which I didn’t on this page, and didn’t care to).  Furthermore I wanted to do it in PowerShell.  The biggest unknown to me was the simplest way to find all the empty folder.  If I could get that, then the rest should be easy.  I quickly found a technet tip{{3}} that showed a simple way to do that.  The rest was pretty simple from there.  It’s quick and dirty, but did the job.

I am doing this in two steps.  Many of you PowerShell gurus will probably judge me for not doing it in one.  But I like to break things up into simple logical steps for clarity.

The first step was to enumerate all of the folder object from the desired directory into an array.

$allFolders = Get-ChildItem C:\targetfolder -recurse | Where-Object {$_.PSIsContainer -eq $True}

From there is was a simple matter of using a ForEach and  and an If statement to interate through each object and delete it if it was empty

ForEach ($folder in $allFolders){if ($folder.GetFiles().Count -eq-and $folder.GetDirectories().Count –eq 0){rmdir $folder.FullName}}

Now there is one major flaw with this approach.  Since it is looking at a single directory at a time, you can’t delete an entire chain of empty directories with a single pass.  This only deletes folders that don’t have a file or folder in them (the deepest folder in a chain)  This is because this script does not know if the sub-folder has a file or not until it gets to it.  You may have to run these several times to get all the directories deleted.  Of course  we could write more logic around this to loop the “delete loop” until there is nothing left to delete.  But this was sufficient for my needs (it only took two passes for me).

Hope it helps.

[[1]]http://technet.microsoft.com/en-us/library/bb978526.aspx[[1]]
[[2]]http://blogs.msdn.com/b/oldnewthing/archive/2008/04/17/8399914.aspx[[2]]
[[3]]http://technet.microsoft.com/en-us/library/ff730953.aspx[[3]]