我正在尝试编写一个脚本来查看一组文件夹并仅保留最后 10 个文件。每个文件夹中的文件可以每天、每周或每月创建。我需要脚本来保留 10 个最新副本,无论创建日期或修改日期如何。
使用另一篇文章,我创建了下面的脚本,该脚本可以运行,但它不会保留 10 个副本,它会保留不超过 10 天的任何文件。
$ftppath = "C:\Reports"
Get-ChildItem $ftppath -recurse *_Report_*.zip -force|where {$_.lastwritetime -lt (get-date).adddays(-10)} |Remove-Item -force
关于如何调整它以使其工作有什么想法吗?如果我使用下面的脚本,它可以工作,但前提是我不设置 -Recurse。如果您使用 -Recurse 开关,您会收到我在脚本下方列出的错误。
# Keeps latest 10 files from a directory based on Creation Time
#Declaration variables
$path = "C:\Reports" # For example $path= C:\log\*.tmp
$total= (ls $path).count - 10 # Change number 5 to whatever number of objects you want to keep
# Script
ls $path |sort-object -Property {$_.CreationTime} | Select-Object -first $total | Remove-Item -force
Error: Select-Object : Cannot validate argument on parameter 'First'. The -7 argument is less than the minimum allowed range of 0. Supply an argument that is greater than 0 and then try the command again.
最佳答案
您可以按CreationTime
降序排序并跳过前 10 个。如果文件少于 10 个,则不会删除任何文件。
gci C:\temp\ -Recurse| where{-not $_.PsIsContainer}| sort CreationTime -desc|
select -Skip 10| Remove-Item -Force
关于powershell - 保留 x 个文件并删除所有其他文件 - Powershell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8810580/