繁体   English   中英

Powershell 脚本以递归方式删除每个文件夹中的文件,除了最近写入时间的 10 个文件夹

[英]Powershell Script to delete files recursively in every folder except 10 with the most recent write time

我想写一个脚本作为标题。 我在递归地做这件事上遇到了麻烦,所以我试着在参数中传递路径。 问题是,当我将 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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM