我只想删除一个特定文件夹中超过15天前创建的文件。我如何使用PowerShell做到这一点?


当前回答

试试这个:

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

其他回答

$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

这将删除旧文件夹和它的内容。

试试这个:

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

基本上,迭代给定路径下的文件,从当前时间中减去每个文件的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

如果你在Windows 10系统上使用上述示例有问题,请尝试将. creationtime替换为. lastwritetime。这对我很管用。

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

另一种选择(15。自动输入[timespan]):

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