[英]Powershell Script to delete files recursively in every folder except 10 with the most recent write time
I would like to write a script as in a title.我想写一个脚本作为标题。 I have been getting trouble with doing it recursively, so i tried just passing path in argument.我在递归地做这件事上遇到了麻烦,所以我试着在参数中传递路径。 The problem is, when i pass 1 argument to the script it works properly, but when I start passing more, it doesn't skip 10 files in next folders, it skips the right amount of files only in the first folder.问题是,当我将 1 个参数传递给脚本时,它可以正常工作,但是当我开始传递更多参数时,它不会跳过下一个文件夹中的 10 个文件,它只会跳过第一个文件夹中的正确数量的文件。 If anyone can help doing it recursively and passing only path to the parent directory or just passing every path separately, I would be pleased.如果有人可以帮助递归地执行此操作并仅将路径传递给父目录或仅单独传递每个路径,我会很高兴。 Here is my code, it works properly only with the first passed argument.这是我的代码,它仅适用于第一个传递的参数。
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
Since you pass the entire array to Get-ChildItem, it will pipe all files in all the directories to be sorted att once.由于您将整个数组传递给 Get-ChildItem,因此它将 pipe 所有目录中的所有文件一次排序。 Try wrapping your entire pipe in a foreach.尝试将整个 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.