[英]Powershell delete folder files based on date range criteria
Below command, delete files older than 30 days在命令下方,删除超过 30 天的文件
Get-ChildItem –Path "C:\path\to\folder" -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-30))} | Remove-Item
But how to add filters, that dont delete files if但是如何添加过滤器,如果不删除文件
date is 1st of each month or
date is 15th of each month or
date is 30
also ignore files with name '%weekly%'
Since you only want to remove files , you should use the -File
switch on the Get-ChildItem
.由于您只想删除文件,您应该使用
Get-ChildItem
上的-File
开关。 In order not to keep calculating the reference date 30 days ago, I like to define that in a variable $refDate
first.为了不继续计算 30 天前的参考日期,我喜欢先在变量
$refDate
定义它。 Also, you should use the date, as of midnight by setting the time part to 00:00:00
.此外,您应该通过将时间部分设置为
00:00:00
来使用截至午夜的日期。 That is where property Date
comes in.这就是属性
Date
用武之地。
$refDate = (Get-Date).AddDays(-30).Date # set it to midnight
Get-ChildItem -Path "C:\path\to\folder" -File -Recurse |
Where-Object { ($_.LastWriteTime -lt $refDate) -and
($_.BaseName -notlike '*%weekly%*') -and
(1,15,30 -notcontains $_.LastWriteTime.Day)} |
Remove-Item -WhatIf
PS I have added the -WhatIf
switch, so you can see what would happen first. PS 我已经添加了
-WhatIf
开关,所以你可以看到首先会发生什么。 If you are satisfied with the messages in the console, remove this switch to actually start deleting files如果您对控制台中的消息感到满意,请删除此开关以实际开始删除文件
You can go for powershell script like below:您可以使用如下所示的 powershell 脚本:
$FolderName = "c:\dev\test"
foreach($file in (GEt-childitem -Path $FolderName -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-30))} ))
{
if (($file.lastwritetime.Date.Day -in 1,15,30 ) -or ($file -like '*weekly*'))
{
continue
}
Remove-Item -Path $file.FullName
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.