1

we got a small script that creates folders named by the daily date. I got a script that deletes folders which are older than 30 days.

dir "\\nas\Backup_old\*" -ErrorAction SilentlyContinue |
Where { ((Get-Date) - $_.LastWriteTime).days -gt 30} |
Get-ChildItem -Recurse | Remove-Item -Recurse -Force

Principally it works fine. The Subfolders with contend will be deleted. But the main folder is still existing and the LastWriteTime is canged to the runtime of the script. The folder is empty. Someone have a idea to solve this problem?

Fab
  • 13
  • 2
  • I think you can look fol emty folders en delete folders look here hihttps://stackoverflow.com/questions/28631419/how-to-recursively-remove-all-empty-folders-in-powershell – Kemal K. Oct 19 '18 at 11:06

1 Answers1

3

You probably just need to remove the second instance of Get-ChildItem (noting that dir is just an alias for Get-ChildItem), as that is causing it to remove the children of each of the directories returned by the first:

Get-ChildItem "\\nas\Backup_old\*" -ErrorAction SilentlyContinue |
    Where-Object { ((Get-Date) - $_.LastWriteTime).days -gt 30} |
    Remove-Item -Recurse -Force -WhatIf

Have a look at the WhatIf output and if it looks like it will now remove what you expect, remove -WhatIf.

Mark Wragg
  • 22,105
  • 7
  • 39
  • 68