Here's a PowerShell script that removes empty folders recursively:
PowerShell
$rootFolder = 'C:\Temp'
Get-ChildItem $rootFolder -Recurse -Directory -Force |
Sort-Object -Property FullName -Descending |
Where-Object { $($_ | Get-ChildItem -Force | Select-Object -First 1).Count -eq 0 } |
Remove-Item
The logic is as follows:
- Get all directories recursively; use
-Force to include hidden folders - Sort them in descending order to ensure the deepest folders are removed first
- Filter out non-empty folders
- Remove the folder
Do you have a question or a suggestion about this post? Contact me!