I DO NOT want to "delete files older than X days." If I wanted to do this, I'd just pick one of the thousands of scripts out there that have already been written for that purpose, and I wouldn't bother asking such a trivial question on ServerFault.
I DO want to delete all but the most recent N files in a particular folder.
I found a script that does what I need, but it works in a specific folder. Here is the script:
# Defines how many files you want to keep?
$Keep = 2
# Specifies file mask
$FileMask = "*.bak"
# Defines base directory path
$Path = "D:\example\"
# Creates a full path plus file mask value
$FullPath = $Path + $FileMask
# Creates an array of all files of a file type within a given folder, reverse sort.
$allFiles = @(Get-ChildItem $FullPath) | SORT Name -descending
# Checks to see if there is even $Keep files of the given type in the directory.
If ($allFiles.count -gt $Keep) {
# Creates a new array that specifies the files to delete, a bit ugly but concise.
$DeleteFiles = $allFiles[$($allFiles.Count - ($allFiles.Count - $Keep))..$allFiles.Count]
# ForEach loop that goes through the DeleteFile array
ForEach ($DeleteFile in $DeleteFiles) {
# Creates a full path and delete file value
$dFile = $Path + $DeleteFile.Name
# Deletes the specified file
Remove-Item $dFile
}
}
I wonder if there is any way for me to make this script work on an entire disk. For example, it scans Disk D, and enters each subfolder and deletes files, keeping the two most recent ones. Deleting only files and not folders.