(Get-ChildItem -recurse | Where-Object {$_.PSIsContainer -eq $True}) |
Where-Object {$_.GetFiles().Count -eq 0} | remove-item
UPDATE:
Chad Rexin has corrected this code:
(Get-ChildItem -recurse | Where-Object {$_.PSIsContainer -eq $True}) |
Where-Object {$_.GetFiles().Count -eq 0 -AND $_.GetDirectories().Count -eq 0} |
ForEach-Object {Write-Host “Deleting this empty directory $($_.FullName)”;
remove-item $_.FullName}
See below for discussion.
This could end up deleting directories that have subdirectories under them and that those subdirectories could have some files in them that you don’t want to delete. To make this safer to run you should change it to also check if there are any directories that exist in a particular directory or not as well like the sample I’ve included below. Ideally there should also be some more try/catch type logic and error checking/handling, but this is some nice quick and easy code.
(Get-ChildItem -recurse | Where-Object {$_.PSIsContainer -eq $True}) |
Where-Object {$_.GetFiles().Count -eq 0 -AND $_.GetDirectories().Count -eq 0} |
ForEach-Object {Write-Host “Deleting this empty directory $($_.FullName)”;
remove-item $_.FullName}
LikeLike
Thank you very much!
I did not know this. I thought an empty dir would truly mean an empty dir.
LikeLike