保留 x 个文件并删除所有其他文件 - Powershell [英] Keep x number of files and delete all others - Powershell

查看:52
本文介绍了保留 x 个文件并删除所有其他文件 - Powershell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个脚本,该脚本将查看一组文件夹并仅保留最后 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 开关,则会出现我在脚本下方列出的错误.

# 根据创建时间保留目录中最新的 10 个文件#声明变量$path = "C:\Reports" # 例如 $path= C:\log\*.tmp$total= (ls $path).count - 10 # 将数字 5 更改为您想要保留的任意数量的对象# 脚本ls $path |sort-object -Property {$_.CreationTime} |选择对象 -first $total |Remove-Item -force

<块引用>

错误:选择对象:无法验证参数First"上的参数.-7 参数小于允许的最小范围 0.提供一个大于 0 的参数,然后重试该命令.

解决方案

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

gci C:\temp\ -Recurse|where{-not $_.PsIsContainer}|排序创建时间 -desc|选择 -跳过 10|Remove-Item -Force

I am trying to write a script that will look through a set of folders and keep only the last 10 files. The files in each folder could be created daily, weekly or monthly. I need the script to keep the 10 most recent copies regardless of the creation date or modified date.

Using another post I created the script below that works but it doesnt keep 10 copies it keeps any file that isn't older than 10 days.

$ftppath = "C:\Reports"
Get-ChildItem $ftppath -recurse *_Report_*.zip -force|where {$_.lastwritetime -lt (get-date).adddays(-10)} |Remove-Item -force

Any idea on how I can tweak this to work? If I use the script below it works but only if I dont set -Recurse. If you use the -Recurse switch you get an error that I have listed below the script.

# 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.

解决方案

You can sort by CreationTime descending and skip the first 10. If there are less than 10 files it will not remove any.

gci C:\temp\ -Recurse| where{-not $_.PsIsContainer}| sort CreationTime -desc| 
    select -Skip 10| Remove-Item -Force

这篇关于保留 x 个文件并删除所有其他文件 - Powershell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆