0

I have directory with about 12k folders with multiple subfolders inside.

I'm trying to remove all empty folders older than defined days, but the thing is not to remove folder (which last write time matches the limit), which has "younger" subfolder inside.

Using one of (many found), examples (which I modified a bit), I got really close, but unfortunately it got rid of prepared folder also (I created file in test folder to check if it will be deleted).

It appears that it doesn't really go through all sub folders.

Here is code:

$limit = (Get-Date).AddDays(-180)
$path = "path"

Get-ChildItem -Path $path -Recurse -Force | Where-Object {
  ($_.PSIsContainer -and $_.LastWriteTime -lt $limit) -and
  (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object {
    !$_.PSIsContainer
  }) -eq $null
} | Remove-Item -Force -Recurse

Any ideas what am I doing wrong with it?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
michu
  • 11
  • 3
  • should it not remove directories that are older then 180 days but not empty? – 4c74356b41 Nov 10 '16 at 15:06
  • You'll need to loop through the process more than once as you are deleting directories the results of Get-ChildItem are changing. Take a look at this to help you out: http://stackoverflow.com/questions/28631419/how-to-recursively-remove-all-empty-folders-in-powershell – henrycarteruk Nov 10 '16 at 15:12
  • Just a comment for you - you can run this against your actual folders, just add the -WhatIf flag – Chris N Nov 10 '16 at 19:00
  • Thank you for all replies, I tried to make some changes with tips provided by James C., but it didn't work, it left more folders than previous versions, but still deletes prepared folder. I've put `do` above first GCI, and created two variables inside (pretty much same thing like in linked post - one variable for defining folders, and second only to remove). It shouldn't delete "Parent folder" (which is older), if child is younger. Chris, can you give any hint where to put `--WhatIf`? – michu Nov 14 '16 at 11:51

0 Answers0