且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 PowerShell 删除超过 15 天的文件

更新时间:2023-12-04 21:10:52

给出的答案只会删除文件(这当然是本文标题中的内容),但这里有一些代码会首先删除所有文件超过 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.