问题
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
}
回答1:
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
}
}
来源:https://stackoverflow.com/questions/8914763/keep-x-number-of-files-and-delete-all-others-part-two