ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software

Cleaning a pc: recursive delete all empty folders with powershell help

Updated on September 15, 2014
Source

I've been using powershell to automatize some tedious tasks done through visual interface on windows, this is a powerful tool and I recommend everybody with some programmatic to check it out.

The powershell is an advanced command line console, like the old MS-DOS or a terminal in Linux systems, but with improved option, so programmers and system administrators can use it more efficiently.

The last task has been removing empty directories in hierarchy, so the deepest directory being empty will be deleted, the parent, when all children directories are deleted for being empty will be deleted if it's empty, that's the main idea.I've taken an already posted script [in links section] by Guy Ellis on his blog to delete empty folders and taken one step further, I've created a recursive function for this deletion that is being called before the check of the content of the directory.

The function is this:

function recursiveDeleteEmptyDirs([string]$dir = "./")
{
 $items = Get-ChildItem -Path $dir
 
 foreach($item in $items)
 {
  if( $item.PSIsContainer )
  {
   recursiveDeleteEmptyDirs $item.FullName
   $subitems = Get-ChildItem -LiteralPath $item.FullName
   if($subitems -eq $null)
   {
    "Remove item: " + $item.FullName
    Remove-Item -Force -Recurse $item.FullName
   }
   $subitems = $null
  }
 }
}

Edit:

I've found some problem in the second get-childitem for some dir-names with strange character, probably can be changed to some other cmdlet to know if the current dir is empty

And remember to give any insight you consider appropiate. Thanks!

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.