Windows Powershell: Remove files older than specific date.

I recently have been trying to find a method that would allow me to clean up a bunch of old files wihtout having to manually continually keep doing the process of manually selecting files and deleting them. This script seems to be good to do exactly that. The requirement was to find any files that had been added/modified within a folder structure after a certain date.

#remove files by a specific date
get-childitem “some folder” -recurse | where-object {$_.mode -notmatch “d”} | where-object {$_.lastwritetime -gt [datetime]::parse(“18/07/2010”)} | format-table lastwritetime, fullname -autosize | out-file newfiles.log -append

Explanation:

get-childitem is equivalent to the DOS (or PowerShell!) dir command, -recurse is fairly obvious, similar to dir /s
where-object allows you to filter out stuff based on criteria being true (or false if you use {-not (code)}. The $_.mode “d” parameter marks folders (aka directories) and -notmatch therefore means we only pass on things that are not folders. lastwritetime is the NTFS last modified date/time, a bit of fiddling is required to get the date into a format that -gt (greater than) can handle (but only if you are not used to using American date formatting of mm/dd/yyyy or UTC style yyyy/mm/dd – if I had written the date as 07/18/2010 or 2010/07/18 the [datetime]::parse() is not required – not very intuitive as the date is listed in the localised format in the output of this script, in my case dd/mm/yyyy).
format-table allows you to get the output in table format (vs list, custom, wide), to specify which columns you’re interested in, and -autosize stops it being stupid (loads of padding after the date/time and truncated filenames/paths)
out-file send the output to a file, and -append does as you’d expect, and can still be used if the file does not already exist

Leave a Reply

Your email address will not be published. Required fields are marked *