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


186

我只想删除15天以上在特定文件夹中创建的文件。如何使用PowerShell执行此操作?


5
大多数答案使用CreationTime,但是在复制文件时会重置它,因此您可能无法获得所需的结果。LastWriteTime对应于Windows资源管理器中的“修改日期”。
罗兰·舍尔

Answers:


308

给定的答案只会删除文件(这当然是帖子标题),但这是一些代码,它将首先删除所有早于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

当然,如果要在实际删除文件/文件夹之前先查看将删除哪些文件/文件夹,则只需在两行末尾将-WhatIf开关添加到Remove-Itemcmdlet调用中即可。

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


22
感谢您不使用别名。对于刚接触Powershell并通过Google搜索找到此帖子的人,我认为您的答案是最好的。
Geoff Dawdy 2013年

1
我尝试了@deadlydog的建议,无论是否指定-15或-35,并且文件创建日期可以追溯到几个月(或最近),它都会删除目录的全部内容。
米歇尔

6
如果可能正在使用文件,则还应在RemoveItem命令中添加“ -ErrorAction SilentlyContinue”。
凯文·欧文

17
谢谢!我使用$ _。LastwriteTime而不是$ _。CreationTime
Lauri Lubi

2
该脚本中的第二个命令始终会得到一个错误,即Get-ChildItem无法找到路径的一部分。它得到一个找不到目录异常。但是,它可以毫无问题地删除空文件夹。不知道为什么在工作时仍然出错。
内森·麦卡斯凯尔

51

只是简单地(PowerShell V5)

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

16

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

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

Get-ChildItem $root -Recurse | ? {
  -not $_.PSIsContainer -and $_.CreationTime -lt $limit
} | Remove-Item

13

基本上,您遍历给定路径下的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

8

试试这个:

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

我相信最后-recurse一个太多了,不是吗?目录列表是递归的,删除项不应该包含子项,对吗?
Joost 2013年

如果您正在使用的目录是两个目录,则需要第二个-recurse。
Bryan S.

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

1
我已经将答案更新为现在排除目录,谢谢。
KERR

3

另一种选择(15.自动键入[timespan]):

ls -file | where { (get-date) - $_.creationtime -gt 15. } | Remove-Item -Verbose

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

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

这将删除旧文件夹及其内容。


0

如果您有在Windows 10盒上面的例子中的问题,请尝试更换.CreationTime.LastwriteTime。这对我有用。

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

LastwriteTime与并不相同CreationTimeLastwriteTime每次修改文件时都会更新。
MisterSmith

-1
#----- Define parameters -----#
#----- Get current date ----#
$Now = Get-Date
$Days = "15" #----- define amount of days ----#
$Targetfolder = "C:\Logs" #----- define folder where files are located ----#
$Extension = "*.log" #----- define extension ----#
$Lastwrite = $Now.AddDays(-$Days)

#----- Get files based on lastwrite filter and specified folder ---#
$Files = Get-Children $Targetfolder -include $Extension -Recurse | where {$_.LastwriteTime -le "$Lastwrite"}

foreach ($File in $Files)
{
    if ($File -ne $Null)
    {
        write-host "Deleting File $File" backgroundcolor "DarkRed"
        Remove-item $File.Fullname | out-null
    }
    else
        write-host "No more files to delete" -forgroundcolor "Green"
    }
}

而且,它永远不会到达else语句,因为如果$Files为空,则不会输入foreach语句。您应该将foreach放在if语句中。
Dieter

@mati实际上它可以到达else语句。我们基于文件列表有一个类似的for循环,它会定期使用$ File变量进入null的for循环
BeowulfNode42 2015年

我猜-只是停留在同一脚本上;networknet.nl/apps/wp/published/...
Shawson
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.