Powershell-删除旧文件夹,但不删除旧文件 [英] Powershell - delete old folders but not old files

查看:207
本文介绍了Powershell-删除旧文件夹,但不删除旧文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将以下代码保留在不再需要保留的旧文件夹之上

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

它将删除超过($ limit)天的特定天数的所有内容,包括文件和文件夹. 但是,我要做的只是删除旧文件夹及其内容.

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.

例如,一个日日文件夹可能包含一个已存在一年的文件,但我想保留该文件夹和旧文件.上面的代码保留文件夹,但删除文件.我要做的就是删除根目录中早于 $ limit 的文件夹(及其内容),否则不理会其他文件夹和内容.

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.

谢谢.

推荐答案

请看一下此位:

 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.

第二部分只是删除空文件夹,您可以按原样保留它,也可以添加到Where语句中以包含CreationTime:

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

第二个Where语句返回一个比$ limit更新的文件和文件夹的列表,并且仅在该文件夹为null时删除该文件夹.

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

这篇关于Powershell-删除旧文件夹,但不删除旧文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆