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


3 comments:

  1. windows server 2008, Standard Edition taking on the bulk of network services, the Enterprise Edition is really focused on server systems that require extremely large-scale processing and memory capabilities as well as clustering or Active Directory Federation Services.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. This is very helpful information for my business regarding subscription management system. Thanks for providing it.

    ReplyDelete

Note: Only a member of this blog may post a comment.