powershellwindows-8.1

How to recursively remove all empty folders in PowerShell?


I need to recursively remove all empty folders for a specific folder in PowerShell (checking folder and sub-folder at any level).

At the moment I am using this script with no success.

Could you please tell me how to fix it?

$tdc='C:\a\c\d\'
$a = Get-ChildItem $tdc -recurse | Where-Object {$_.PSIsContainer -eq $True}
$a | Where-Object {$_.GetFiles().Count -eq 0} | Select-Object FullName

I am using PowerShell on Windows 8.1 version.


Solution

  • You can use this:

    $tdc="C:\a\c\d"
    $dirs = gci $tdc -directory -recurse | Where { (gci $_.fullName).count -eq 0 } | select -expandproperty FullName
    $dirs | Foreach-Object { Remove-Item $_ }
    

    $dirs will be an array of empty directories returned from the Get-ChildItem command after filtering. You can then loop over it to remove the items.

    Update

    If you want to remove directories that contain empty directories, you just need to keep running the script until they're all gone. You can loop until $dirs is empty:

    $tdc="C:\a\c\d"
    do {
      $dirs = gci $tdc -directory -recurse | Where { (gci $_.fullName).count -eq 0 } | select -expandproperty FullName
      $dirs | Foreach-Object { Remove-Item $_ }
    } while ($dirs.count -gt 0)
    

    If you want to ensure that hidden files and folders will also be removed, include the -Force flag:

    do {
      $dirs = gci $tdc -directory -recurse | Where { (gci $_.fullName -Force).count -eq 0 } | select -expandproperty FullName
      $dirs | Foreach-Object { Remove-Item $_ }
    } while ($dirs.count -gt 0)