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

use*_*170 175 powershell powershell-2.0 powershell-3.0

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

dea*_*dog 287

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

$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
Run Code Online (Sandbox Code Playgroud)

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

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

  • 感谢您不使用别名.对于刚接触过PowerShell并通过Google搜索发现此帖子的人,我认为您的答案是最好的. (20认同)
  • 谢谢!我使用$ _.LastwriteTime而不是$ _.CreationTime (15认同)
  • 如果文件可能正在使用中,则还需要在RemoveItem命令中添加"-ErrorAction SilentlyContinue". (6认同)
  • 该脚本中的第二个命令始终会收到Get-ChildItem无法找到路径部分的错误.它获取目录未找到异常.然而,它删除空文件夹没有问题.不知道为什么它会在工作时出错. (2认同)

Esp*_*o57 41

只是简单(PowerShell V5)

Get-ChildItem "C:\temp" -Recurse -File | Where CreationTime -lt  (Get-Date).AddDays(-15)  | Remove-Item -Force
Run Code Online (Sandbox Code Playgroud)


Ans*_*ers 16

另一种方法是从当前日期减去15天并CreationTime与该值进行比较:

$root  = 'C:\root\folder'
$limit = (Get-Date).AddDays(-15)

Get-ChildItem $root -Recurse | ? {
  -not $_.PSIsContainer -and $_.CreationTime -lt $limit
} | Remove-Item
Run Code Online (Sandbox Code Playgroud)


Sha*_*evy 14

基本上,您迭代给定路径下的文件,减去CreationTime从当前时间找到的每个文件,并Days与结果的属性进行比较.该-WhatIf交换机会告诉你并没有实际删除的文件(文件将被删除)会发生什么,删除开关实际删除文件:

$old = 15
$now = Get-Date

Get-ChildItem $path -Recurse |
Where-Object {-not $_.PSIsContainer -and $now.Subtract($_.CreationTime).Days -gt $old } |
Remove-Item -WhatIf
Run Code Online (Sandbox Code Playgroud)


Rol*_*sen 7

试试这个:

dir C:\PURGE -recurse | 
where { ((get-date)-$_.creationTime).days -gt 15 } | 
remove-item -force
Run Code Online (Sandbox Code Playgroud)


Jef*_*hal 6

如果您在 Windows 10 机器上使用上述示例时遇到问题,请尝试替换.CreationTime.LastwriteTime. 这对我有用。

dir C:\locationOfFiles -ErrorAction SilentlyContinue | Where { ((Get-Date)-$_.LastWriteTime).days -gt 15 } | Remove-Item -Force
Run Code Online (Sandbox Code Playgroud)


KER*_*ERR 5

Esperento57的脚本在较旧的PowerShell版本中不起作用.这个例子做了:

Get-ChildItem -Path "C:\temp" -Recurse -force -ErrorAction SilentlyContinue | where {($_.LastwriteTime -lt  (Get-Date).AddDays(-15) ) -and (! $_.PSIsContainer)} | select name| Remove-Item -Verbose -Force -Recurse -ErrorAction SilentlyContinue
Run Code Online (Sandbox Code Playgroud)