Powershell - delete old folders but not old files

邮差的信 提交于 2019-12-12 05:29:26

问题


I have the following code to keep on top of old folders which I no longer want to keep

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

It deletes anything older than a certain number of days ($limit) including files and folders. However, what I am after is ONLY deleting old folders and their contents.

For example, a day old folder may have file within that is a year old but I want to keep that folder and the old file. The code above keeps the folder but deletes the file. All I want to do is delete folders (and their contents) within the root that are older than the $limit else leave the other folders and content alone.

Thanks in advance.


回答1:


Well look at this bit:

 Get-ChildItem -Path $path -Recurse -Force -EA SilentlyContinue| 
  Where-Object { !$_.PSIsContainer -and $_.CreationTime -ge $limit } |
   Remove-Item -Force -EA SilentlyContinue

It's basically saying "everything not a folder and older than specified is removed". So your first step is to remove that.

The second part is just deleting empty folders, you can keep it as-is or you could add to the Where statement to include the CreationTime:

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

The second Where statement returns a list of files and folders newer than $limit, and only deletes the folder if that is null.



来源:https://stackoverflow.com/questions/35936490/powershell-delete-old-folders-but-not-old-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!