In my previous blog posts, I have shared various Windows PowerShell scripts that focus on file management, such as moving or deleting files. One common question I have received is how to delete automatically empty folders efficiently. Therefore, I will concisely explain this topic in this article.
When dealing with file organization and cleanup, it’s not uncommon to come across empty folders that are no longer needed. Deleting them manually can be time-consuming, especially if numerous empty folders are scattered throughout the file system. This is where PowerShell comes in handy.
We can create a script that automatically identifies and removes empty folders by utilizing PowerShell, saving us valuable time and effort. In this article, I will walk you through the steps and provide an example script to accomplish this task effectively.
Delete empty folders with Powershell.
Most of the requests I received were related to the “Delete files older than x days” article. As a result of this script, orphaned directories were not removed after no more files were in them. This can also be intentional in specific environments, but the directories are no longer required in most cases.
PowerShell does not offer a standard cmdlet for this, but it is easy to write your function. The following short script creates a new function that you can use to delete empty folders and also remove subdirectories.
function Remove-EmptyFolders([string]$folders){
Get-Childitem $folders -Recurse | Where-Object {$_.PSIsContainer -and !(Get-Childitem $_.Fullname -Recurse |
Where-Object {!$_.PSIsContainer})} | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
}
The function is then about the command Remove-EmptyFolders accessible. The only parameter that needs to be specified is the folder in which the search for empty directories will ultimately be carried out. This means that all empty subdirectories of this folder will be removed.
The following example thus deletes all subfolders of the C: TempTest folder:
Remove-EmptyFolders C:TempTest
A variable in which the folder was saved can also be specified as a parameter. This is especially useful for scripts applied to specific folder structures.