We have already shown you how flexible the Linux shell can be, but that’s not to say Windows is any further behind. Here’s two techniques you can use depending on your shell preference, cmd or PowerShell.
我们已经向您展示了Linux shell的灵活性 ,但这并不是说Windows会进一步落后。 您可以根据外壳程序的偏好使用以下两种技术:cmd或PowerShell。
PowerShell 3 (PowerShell 3)
Get-ChildItem –Path “C:\Backups” –Recurse | Where-Object CreationTime –lt (Get-Date).AddDays(-5) | Remove-Item
Get-ChildItem –路径“ C:\ Backups” –递归| 对象创建时间-lt(Get-Date).AddDays(-5)| 除去项目
PowerShell 2 (PowerShell 2)
Get-ChildItem –Path “C:\Backups” –Recurse | Where-Object{$_.CreationTime –lt (Get-Date).AddDays(-5)} | Remove-Item
Get-ChildItem –路径“ C:\ Backups” –递归| Where-Object {$ _。CreationTime –lt(Get-Date).AddDays(-5)} | 除去项目
Explanation
说明
- Firstly we get FileInfo and DirectoryInfo objects in the Path C:\Backups. 首先,我们在路径C:\ Backups中获得FileInfo和DirectoryInfo对象。
- FileInfo and DirectoryInfo objects both contain a CreationTime property, so we can filter the collection using that. FileInfo和DirectoryInfo对象都包含CreationTime属性,因此我们可以使用该属性过滤集合。
- The –lt (less than) operator is then used to compare the CreationTime property of the objects with Get-Date (the current date) subtract 5 days. 然后,使用-lt(小于)运算符将对象的CreationTime属性与Get-Date(当前日期)减去5天进行比较。
- This then leaves us with a collection of objects that were created more than 5 days ago, which we pass to Remove-Item. 然后,这为我们提供了5天以上创建的对象的集合,我们将其传递给Remove-Item。
Pro Tip
专家提示
To see what will be removed you can use the –WhatIf parameter:
要查看将删除的内容,可以使用–WhatIf参数:
Get-ChildItem –Path “C:\Backups” –Recurse | Where-Object CreationTime –lt (Get-Date).AddDays(-5) | Remove-Item –WhatIf
Get-ChildItem –路径“ C:\ Backups” –递归| 对象创建时间-lt(Get-Date).AddDays(-5)| 删除项目–WhatIf
命令提示符 (Command Prompt)
While we recommend you use one of the PowerShell methods, without getting into any of the gritty details you can also do it from command prompt.
尽管我们建议您使用PowerShell方法之一,但无需深入了解任何棘手的细节,您也可以从命令提示符处进行操作。
forfiles -p "C:\Backups" -s -m *.* -d -5 -c "cmd /c del @path"
forfiles -p“ C:\ Backups” -s -m *。* -d -5 -c“ cmd / c del @path”
Pro Tip
专家提示
To see what files are going to be deleted you can use echo.
要查看要删除哪些文件,可以使用echo。
forfiles -p "C:\Backups" -s -m *.* -d -5 -c "cmd /c echo @file"
forfiles -p“ C:\ Backups” -s -m *。* -d -5 -c“ cmd / c echo @file”
翻译自: https://www.howtogeek.com/131881/how-to-delete-files-older-than-x-days-on-windows/