Saturday, December 12, 2020

Delete Empty Folders with Powershell Recursively

In this blog, I'd like to show you the little one-liner powershell code that will delete empty folders recursively. 

Note: Even if there is a single file in the child nested folder, it will exclude the parent path from deletion.

For example, we will create folder tree like this in Fig-1.1.

Fig-1.1: The folder structure

 If you're not sure & want to see which files will be deleted, you can run the following one-liner.

(gci -Directory -R) | ?{$_.GetFileSystemInfos().Count -eq 0}  | select Attributes,Fullname

But, you will not see the folder child2 (but it will be deleted finally) in the current directory because it doesn't know ahead that its sub-folders are empty or not. See Fig-1.2.

Fig-1.2: Showing the folder which are missing from preview

Then we run the following command for recursive empty folder deletion. You can remove -verbose if you don't want to see the messy output ;D

while   ((gci -Directory -R) |  ? {$_.GetFileSystemInfos().Count -eq 0} )  { (gci -Directory -R) | ?{$_.GetFileSystemInfos().Count -eq 0} | remove-item -Confirm:$false -verbose }

 Then, let's check the remaining files and folders with the previous command (as in Fig-1.1).

 (gci -Directory -R) | ?{$_.GetFileSystemInfos().Count -eq 0}  | select Attributes,Fullname

Fig-1.3: Checking the result