How To Keep A Folder Clean From Old Files?
Author: Frank-Peter (77 Articles)
With PowerShell it is easy to cleanup out-of-date files in a temp folder, log folder, or whatever folder.
This Post shows two approaches:
- Delete All Files Older Than x Days
- Keep The x Youngest Files
How To Delete All Files Older Than x Days?
Let’s say you need to remove all files in %TEMP% and its subdirectories that weren’t modified during the past 10 days:
dir $env:temp –r | ?{$_.LastWriteTime -le (Get-Date).AddDays(-10)} | del
By piping the result of Get-ChildItem (dir) to Where-Object (?), all out-of-date files will be identified by comparing their LastWriteTime property with current date minus 10 days) and piped to Remove-Item (del)
How To Keep The x Youngest Files?
This time, you want to remove all files in %TEMP% except the 50 youngest files with PowerShell V2:
dir $env:temp | sort lastwritetime -des | select -skip 50 | del
By sorting the result of Get-ChildItem (dir) by LastWriteTime in descending order and piping it to Select-Object (select) with setting its Skip parameter to 50, all but the 50 youngest files will be removed. Note that this requires Windows PowerShell V2 because V1’s Select-Object doesn’t have the Skip parameter!
With PowerShell V1, you could save the array of files returned by Sort-Object –Descending to a variable, and then process this array from skip count to total count as follows:
$files = dir $env:temp | sort lastwritetime -des $files[50..$files.count] | del
Frank-Peter