Pages

søndag 7. april 2013

PowerShell one-liner: delete files older than X days

In this example we want to delete all files older than two days, recursivley, from the TEMP folder.

First, lets list the files we would like to delete, sorted by LastWriteTime:

Get-ChildItem -LiteralPath $env:TEMP -Recurse -ErrorAction SilentlyContinue -Force | Where-Object {! $_.PSIsContainer -And $_.LastWriteTime -le ([datetime]::Today).AddDays(-1)} | Sort-Object LastWriteTime | Format-Table -Property LastWriteTime,CreationTime,FullName -AutoSize

Now, to simulate a delete, we could use:

Get-ChildItem -LiteralPath $env:TEMP -Recurse -ErrorAction SilentlyContinue -Force | Where-Object {! $_.PSIsContainer -And $_.LastWriteTime -le ([datetime]::Today).AddDays(-1)} | Remove-Item -Force -WhatIf

Remove -WhatIf to actually do it...