powershell - 保留 x 个文件并删除所有其他文件 - Powershell

标签 powershell powershell-2.0

我正在尝试编写一个脚本来查看一组文件夹并仅保留最后 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/

相关文章:

powershell - Powershell get-eventlog消息列太短

powershell - 将目录的父目录与where管道中的另一个目录进行比较

powershell - "Start-Process -NoNewWindow"在开始工作中?

powershell - 将powershell脚本更改为不带省略号的输出(…)

powershell - 如何使用Powershell获取事件消息?

powershell - 如何在 PowerShell 中获得正确(规范)大小写的路径?

asp.net - OpenCover 显示没有结果 asp net core 461

powershell - 从 WiX 静默执行 PowerShell 脚本挂起 PowerShell

json - 使用Powershell脚本对JSON响应进行排序

exception - 如何捕获另一个 Powershell 脚本中抛出的异常?