【问题标题】:Powershell Script to delete files recursively in every folder except 10 with the most recent write timePowershell脚本以递归方式删除每个文件夹中的文件,除了最近写入时间的10个文件夹
【发布时间】:2020-07-21 12:08:44
【问题描述】:

我想写一个像标题一样的脚本。我在递归地做这件事上遇到了麻烦,所以我试着在参数中传递路径。问题是,当我将 1 个参数传递给脚本时,它可以正常工作,但是当我开始传递更多参数时,它不会跳过下一个文件夹中的 10 个文件,它只会跳过第一个文件夹中的正确数量的文件。如果有人可以帮助递归地执行此操作并仅将路径传递到父目录或仅单独传递每个路径,我会很高兴。这是我的代码,它仅适用于第一个传递的参数。

Param(
    [string[]]$path
    )



Get-ChildItem $path |

    #skip directories
    Where-Object { -not $_.PsIsContainer } |
    
    #Sort by last write time
    Sort-Object -Descending -Property LastWriteTime | 
    
    #Skip 10 most recent
    Select-Object -Skip 10 |
    
    Remove-Item -whatif

【问题讨论】:

    标签: windows powershell skip


    【解决方案1】:

    由于您将整个数组传递给 Get-ChildItem,因此它将通过管道将所有目录中的所有文件一次性排序。尝试将整个管道包裹在 foreach 中。

    foreach($item in $path){
      Get-ChildItem $item | 
         Where-Object { -not $_.PsIsContainer } | 
         Sort-Object -Descending -Property LastWriteTime | 
         Select-Object -Skip 10 | Remove-Item -whatif
    }
    

    【讨论】:

      猜你喜欢
      • 2010-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-18
      • 1970-01-01
      • 2016-02-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多