Reputation: 627
Below command, delete files older than 30 days
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%'
Upvotes: 1
Views: 5133
Reputation: 61068
Since you only want to remove files, you should use the -File
switch on the Get-ChildItem
.
In order not to keep calculating the reference date 30 days ago, I like to define that in a variable $refDate
first.
Also, you should use the date, as of midnight by setting the time part to 00:00:00
. That is where property Date
comes in.
$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
P.S. I have added the -WhatIf
switch, so you can see what would happen first. If you are satisfied with the messages in the console, remove this switch to actually start deleting files
Upvotes: 4
Reputation: 12959
You can go for powershell script like below:
$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
}
Upvotes: 0