I asked a question about how to go through the directory structure and save the last 7 copies of the file in each subdirectory. The script below is what was created and it works fine, but only in 1 directory. I need to go through the entire directory and save 7 new files in each subdirectory.
For verification, I created a directory structure in C: \ Customer with subdirectories Test1, Test2, Test3. Then I 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 at the top level, Test1, Test2 and saved the last 7 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 }
source share