简体   繁体   English

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

[英]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.

相关问题 删除文件夹和子文件夹中除最近的 3 个文件之外的所有文件 - Deleting all files except the most 3 recent in a folder and sub folders 保留 10 个最近的文件夹并删除其他文件夹 - Keep 10 most recent folders and delete the others 在文件夹/目录中找到最新文件,然后使用Windows cmd或Powershell中的Shell脚本通过电子邮件发送该文件 - Find the most recent file in a folder/dir and send that file in a email using shell script in windows cmd or powershell 在 Windows CMD 上递归删除文件或文件夹 - Delete files or folder recursively on Windows CMD 脚本来选择在分布式系统的文件夹中创建的最新文件? - script to pick the most recent file created in a folder in a distributed system? 如何将最近的两个日志文件复制到另一个文件夹? - How to copy the two most recent log files to another folder? 使用批处理脚本在驱动器上的每个文件夹中查找和删除 desktop.ini 文件 - Find and delete desktop.ini files in every folder on a drive using a batch script 如何以递归方式编写`rar`sa文件夹及其所有内容的脚本? - How to write script that `rar`s a folder and all its content recursively? 编写脚本以在批处理脚本中递归列出其中的目录和文件 - Write a script to recursively list directories and files within it in Batch script 删除Windows批处理脚本中除一个文件夹之外的文件夹? - Delete folders except one folder in windows batch script?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM