Keep x number of files and delete all others - PART TWO

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 } 
+2
source share
1 answer

Unverified, but I think this will do what you need. This will process all directories and save the 7 most recent files in each subdirectory.

 $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 } } 
0
source

Source: https://habr.com/ru/post/1411834/


All Articles