Delete all empty subdirectories

(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.

Advertisements

2 thoughts on “Delete all empty subdirectories

  1. Chad Rexin

    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}

    Like

    Reply
    1. sunea Post author

      Thank you very much!
      I did not know this. I thought an empty dir would truly mean an empty dir.

      Like

      Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s