保留 x 个文件并删除所有其他文件 - 第二部分 [英] Keep x number of files and delete all others - PART TWO

查看:48
本文介绍了保留 x 个文件并删除所有其他文件 - 第二部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之前问过一个关于如何遍历目录结构并在每个子目录中保留文件的 7 个最新副本的问题.下面的脚本是创建的,它运行良好,但仅适用于 1 个目录.我需要遍历整个目录并在每个子目录中保留 7 个最新文件.

I asked a question earlier about how to go through a directory structure and keep the 7 most recent copies of a file in each sub directory. The script below is what was created and it works great but only on 1 directory. I need to to go through the entire directory and keep the 7 newest files in each sub directory.

为了测试,我在 C:\Customer 下创建了一个目录结构,其中包含 Test1、Test2、Test3 的子目录.然后我在每个目录中创建了 12 个测试文件,包括顶级 C:\Customer.这些文件被命名为 Test1_Report_.txt - Test12.当我运行下面的脚本时,它删除了顶层、Test1、Test2 中的所有文件,并在 Test3 中保留了 7 个最近的副本.我在这里缺少什么?任何帮助将不胜感激.

To test I created a directory structure under C:\Customer with sub directories of Test1, Test2, Test3. I then created 12 test files in each directory including the top level C:\Customer. The files were named Test1_Report_.txt - Test12. When I ran the script below it deleted all the files in the top level, Test1, Test2 and kept the 7 most recent copies in Test3. What am I missing here? Any help would be greatly appreciated.

$path = "C:\Customer"


$files = Get-ChildItem -Path $path -Recurse | Where-Object {-not $_.PsIsContainer} |where{$_.name -like "*_Report_*"}
$keep = 7
if ($files.Count -gt $keep) {
    $files |Sort-Object CreationTime |Select-Object -First ($files.Count - $keep)| Remove-Item -Force
}

推荐答案

未经测试,但我认为这可以满足您的需求.这将处理所有目录并在每个子目录中保留 7 个最近的文件.

Untested but I think this will do what you need. This will process all directories and keep the 7 most recent files in each sub directory.

$path = "C:\Customer"
$keep = 7

$dirs = Get-ChildItem -Path $path -Recurse | Where-Object {$_.PsIsContainer}
foreach ($dir in $dirs) {
    $files = Get-ChildItem -Path $dir.FullName | Where-Object {-not $_.PsIsContainer -and $_.name -like "*_Report_*"}
    if ($files.Count -gt $keep) {
        $files | Sort-Object CreationTime | Select-Object -First ($files.Count - $keep) | Remove-Item -Force
    }
}

这篇关于保留 x 个文件并删除所有其他文件 - 第二部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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