-1

I want to delete files older than x days, 5 in the below example. I tried to use below, but its not working nor its throwing an error.

 Get-ChildItem –Path  “E:\del” –Recurse | Where-Object{$_.CreationTime –lt(Get-Date).AddDays(-5)} | Remove-Item
Matt
  • 45,022
  • 8
  • 78
  • 119
MP Martis
  • 43
  • 3
  • 11
  • 3
    You tried to use, good to know. What happened? – Clijsters Mar 27 '17 at 12:27
  • Are you really sure you have version 1 and not getting confused about the directory it resides in: http://stackoverflow.com/questions/1825585/determine-installed-powershell-version? – Matt Mar 27 '17 at 12:38
  • @Clijsters _nor its throwing an error_ that would tell me the `Where-object` clause is not working as he expected. – Matt Mar 27 '17 at 12:39
  • So when you run this: `Get-ChildItem –Path "E:\del" –Recurse | select name, creationtime` that you are seeing files with a create date of older than 5 days? – Matt Mar 27 '17 at 12:41
  • @Matt, got Major 2 , so i have powershell 2 , thanks, does the above script work in version 2 please? – MP Martis Mar 27 '17 at 12:41
  • @Matt yes its giving files older than 5 days when i run the command given by you – MP Martis Mar 27 '17 at 12:43
  • http://stackoverflow.com/questions/28143476/windows-batch-file-to-delete-text-files-older-than-x-days – Mihail Kuznesov Mar 27 '17 at 12:51
  • It worked , i had mistaken creation time with lastModified time, i was copying old files from a old folder to a test folder which made creation time of old files to today's date, Got where i was wrong after seeing output of `Get-ChildItem –Path "E:\del" –Recurse | select name, creationtime` , thanks for the help. – MP Martis Mar 27 '17 at 12:58
  • Ok then. So your code was working but you were filtering on the wrong properties and getting different results than expected. . – Matt Mar 27 '17 at 13:28
  • yes @Matt that's right – MP Martis Mar 27 '17 at 13:52

2 Answers2

2

Here is an approach you could take.

$Path = E:\del
$DaysBack = "-5" 
$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.AddDays($DaysBack)

#delete files from $Path directory that are older than $Daysback
Get-ChildItem -Path $Path -Include * -Recurse | Where-Object {$_.LastWriteTime -lt $DatetoDelete} | Remove-Item -ErrorAction SilentlyContinue -Recurse -Force
Will Webb
  • 795
  • 6
  • 20
-1

Try this:

$cleanup_days = 5
$cleanup_lastWrite = $now.AddDays(-$cleanup_days)

Get-ChildItem -Path "E:\del" | Where-Object { $_ -is [System.IO.FileInfo] } | ForEach-Object {
    If ($_.LastWriteTime -lt $cleanup_lastWrite)
    {
        Remove-Item $("E:\del\" + $_)
    }
}
GitGawd
  • 53
  • 9
  • You need to declare $now or it will throw an error. Try adding `$now = Get-Date` along with your other variables. – Will Webb Apr 20 '17 at 09:40