4

I need to delete all files (recursively in all folders and subfolders) based on their last access time.

I was looking at Stack Overflow post Batch file to delete files older than N days that suggested this answer:

forfiles -p "C:\what\ever" -s -m *.* -d <number of days> -c "cmd /c del @path"

However, this deletes files based on last modified time, not last access time.

Also, is there a way to save the command in a script file so I can just doubleclick it to run?

Community
  • 1
  • 1
robert
  • 1,523
  • 5
  • 19
  • 27

2 Answers2

7

Use Get-ChildItem -recurse to get all the files, you can then pipe them to the where-object commandlet to filter out the directories and use the LastAccessTime property to filter based on that attribute. Then you pipe the result to a foreach-object that executes the delete command.

It ends up looking like this. Note the use of Get-Date, to get all files updated since the start of the year, replace with your own date:

get-childitem C:\what\ever -recurse | where-object {-not $_.PSIsContainer -and ($_.LastAccessTime -gt (get-date "1/1/2012"))} | foreach-object { del $_ }

Or to use some common aliases to shorten everything:

dir C:\what\ever -recurse | ? {-not $_.PSIsContainer -and ($_.LastAccessTime -gt (get-date "1/1/2012"))} | % { del $_ }
zdan
  • 28,667
  • 7
  • 60
  • 71
  • 2
    I would like to add, if you are looking for things that are 7 days old, you can use the `(Get-Date).AddDays(-7)` to do a more variable date. – Nick Sep 12 '12 at 15:26
4

As an aside, this is how you'd do the same (get files only) in PowerShell 3.0:

$old = Get-Date "1/1/2012"

Get-ChildItem C:\what\ever -File -Recurse | 
Where-Object {$_.LastAccessTime -gt $old} | 
Remove-Item -Force
Shay Levy
  • 121,444
  • 32
  • 184
  • 206