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

mpo*_*map 20 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
Run Code Online (Sandbox Code Playgroud)

关于我如何调整这个工作的任何想法?如果我使用下面的脚本它可以工作,但只有我不设置-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
Run Code Online (Sandbox Code Playgroud)

错误:Select-Object:无法验证参数'First'的参数.-7参数小于允许的最小范围0.提供大于0的参数然后再次尝试该命令.

Ryn*_*ant 46

您可以按CreationTime降序排序并跳过前10个.如果少于10个文件,则不会删除任何文件.

gci C:\temp\ -Recurse| where{-not $_.PsIsContainer}| sort CreationTime -desc| 
    select -Skip 10| Remove-Item -Force
Run Code Online (Sandbox Code Playgroud)

  • 啊`-Skip` 简洁明了:-) +1 (2认同)

And*_*ndi 8

更新

$path = "C:\TestDir"

# Create 12 test files, 1 second after each other
1..12 | % {
    Remove-Item -Path "$path\$_.txt" -ea SilentlyContinue
    $_ | Out-File "$path\$_.txt"
    Start-Sleep -Seconds 1
}

$files = Get-ChildItem -Path $path -Recurse | Where-Object {-not $_.PsIsContainer}
$keep = 10
if ($files.Count -gt $keep) {
    $files | Sort-Object CreationTime | Select-Object -First ($files.Count - $keep) | Remove-Item -Force -WhatIf
}
Run Code Online (Sandbox Code Playgroud)

当您准备删除真实时删除-WhatIf参数Remove-Item.