Remove empty folders using PowerShell
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 following:
- Get all directories recursively, use
-Force
to get hidden folders - Sort them in descending order as we want to remove the deepest folders first
- Check if the folder is empty
- Remove the folder
Do you have a question or a suggestion about this post? Contact me!
Enjoy this blog?
💖 Sponsor on GitHub