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.
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
}
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.