![Powershell 脚本删除最旧的文件](https://linux22.com/image/757745/Powershell%20%E8%84%9A%E6%9C%AC%E5%88%A0%E9%99%A4%E6%9C%80%E6%97%A7%E7%9A%84%E6%96%87%E4%BB%B6.png)
我不想“删除超过 X 天的文件”。如果我想这样做,我只需从已经为此目的编写的数千个脚本中选择一个,而且我不会在 ServerFault 上问这么琐碎的问题。
我确实想删除特定文件夹中除最近的 N 个文件之外的所有文件。
我找到了一个可以满足我需求的脚本,但它只在特定文件夹中有效。脚本如下:
# 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
}
}
我想知道是否有办法让这个脚本在整个磁盘上运行。例如,它扫描磁盘 D,进入每个子文件夹并删除文件,保留最近的两个文件。只删除文件而不删除文件夹。