PowerShell – Clean Up Script – Files older than X number of days
I have been working with development teams for many years. One of the most common requests, especially with development and test servers is to automate the deleting of old log or temp file folders. Most of the time these files contain debug information, and do not need archiving, but tend to fill the drives to capacity if not maintained.
To Solve this issue, the following clean up powershell script is useful;
#powershell clean up script based on file write time
gci “e:\temp\*.*”|? {$_.lastwritetime -lt (get-date).adddays(-1)} |
remove-item
To run this script, set the powershell execution policy to RemoteSigned (run the command set-ExecutionPolicy RemoteSigned ) and save the powershell script in a .ps1 file.
To configure the script, change the directory path (e:\temp\*.* in this example) and the number of days required (-1).
To test the script add –whatif after the “remote-item” cmdlet. This will show the files that would be deleted and no data will be lost if errors exist.
Once tested, to schedule it create a batch file with the following (change the powershell file location).
powershell -command “& ‘c:\delete.ps1′ “
You can now schedule the script with the Windows task scheduler (point to the batchfile).


