使用 PowerShell 删除超过 15 天的文件 [英] Delete files older than 15 days using PowerShell

查看:64
本文介绍了使用 PowerShell 删除超过 15 天的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想删除特定文件夹中超过 15 天前创建的文件.我怎么能用 PowerShell 做到这一点?

I would like to delete only the files that were created more than 15 days ago in a particular folder. How could I do this using PowerShell?

推荐答案

给出的答案只会删除文件(这当然是本文标题中的内容),但这里有一些代码会首先删除所有文件超过 15 天,然后递归删除任何可能遗留下来的空目录.我的代码还使用 -Force 选项来删除隐藏和只读文件.另外,我选择不使用别名,因为 OP 是 PowerShell 的新手,可能不明白 gci?% 等是什么.

The given answers will only delete files (which admittedly is what is in the title of this post), but here's some code that will first delete all of the files older than 15 days, and then recursively delete any empty directories that may have been left behind. My code also uses the -Force option to delete hidden and read-only files as well. Also, I chose to not use aliases as the OP is new to PowerShell and may not understand what gci, ?, %, etc. are.

$limit = (Get-Date).AddDays(-15)
$path = "C:\Some\Path"

# Delete files older than the $limit.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force

# Delete any empty directories left behind after deleting the old files.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse

当然,如果您想在实际删除之前查看将删除哪些文件/文件夹,您只需将 -WhatIf 开关添加到 Remove-Item在两行末尾调用 cmdlet.

And of course if you want to see what files/folders will be deleted before actually deleting them, you can just add the -WhatIf switch to the Remove-Item cmdlet call at the end of both lines.

此处显示的代码与 PowerShell v2.0 兼容,但我也将此代码和速度更快的 PowerShell v3.0 代码显示为 我博客上的方便可重用的功能.

The code shown here is PowerShell v2.0 compatible, but I also show this code and the faster PowerShell v3.0 code as handy reusable functions on my blog.

这篇关于使用 PowerShell 删除超过 15 天的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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