Categories

Removing empty folders again

Removing empty folders seems to be a question that crops up on a regular basis. The problem is determining if a folder is empty:

  • it could have subfolders
  • it could have zero length files

Both of these cases would register as empty if all we checked was get-childitem and summed the file sizes especially if subfolders are ignored.

One way to remove empty folders is to use the Scripting Object.  Yes back to VBScript days. Those old COM objects have some mighty fine functionality that we might as well use while its there.

$path = "c:\test"            
$fso = New-Object -ComObject "Scripting.FileSystemObject"            
            
$folder = $fso.GetFolder($path)            
            
foreach ($subfolder in $folder.SubFolders){            
             
 if (($subfolder.Files | Measure-Object).Count -gt 0){continue}            
 if (($subFolders.SubFolders  | Measure-Object).Count -gt 0){continue}            
 if ($subfolder.Size -eq 0 ){Remove-Item -Path $($subfolder.Path) -Force -WhatIf}            
            
}


Create a Scripting.FileSystemObject



Get the folder and for each sub folder check the files and subfolders if either are non zero then ignore (go back to top of loop)



if the sub folder size reports as zero then delete it.  I’ve added the whatif parameter so I can easily test.



This only tests one level of subfolders – if we want them all then its time for some recursion



function remove-emptyfolder {            
 param ($folder)            
             
 foreach ($subfolder in $folder.SubFolders){            
             
 $notempty = $false            
 if (($subfolder.Files | Measure-Object).Count -gt 0){$notempty = $true}            
 if (($subFolders.SubFolders  | Measure-Object).Count -gt 0){$notempty = $true}            
 if ($subfolder.Size -eq 0 -and !$notempty){            
   Remove-Item -Path $($subfolder.Path) -Force -WhatIf            
 }            
 else {            
  remove-emptyfolder $subfolder            
 }            
            
}            
            
}            
            
$path = "c:\test"            
$fso = New-Object -ComObject "Scripting.FileSystemObject"            
            
$folder = $fso.GetFolder($path)            
remove-emptyfolder $folder


 



This is based on the previous script except the folder analysis and deletion is in a folder that calls itself if the current folder has subfolders. The test for files and subfolders are used to set a boolean to help determine whether to delete or perform more analysis

Leave a Reply