Sunday 20 September 2015

Powershell Script for Cleaning up Old Files

Poblem:

I am working on a project that creates 100s of files every hour which has led to creation of over few thousand files in a week. Due to the very high number of files, Explorer takes so long to list the files in the folder. As this could fill up the storage pretty fast, I need to delete files older than 7 days. Please suggest me how best to accomplish this, preferably using PowerShell and leveraging the Scheduled Tasks.

By: Anonymous

Solution:


Powershell is the way to go for these kind of tasks. For deleting old files, the following script will do the job:

Get-ChildItem –Path <Base Folder> –Recurse | Where-Object CreationTime –lt (Get-Date).AddDays(-7) | Remove-Item

Replace the <Base Folder> with the actual base folder  that need to be looked up for this task. Simiarly, you may observe the from the above script, this will delete the files based on the time of creation of the file. If you want to use the last modified time, replace the CreationTime with LastWriteTime

The above script can be executed from the PowerShell prompt or can be scheduled to run automatically using the Windows Task Scheduler. There are couple of things that you should take care of while scheduling:

  • By default, the deletion will fail as the execution policy may not permit the deletion. To override this set the parameter ExecutionPolicy to bypass
  • You may want to add the parameters - noninteractive. to enable to run automatically without needing user action. 
  • Do not place the script itself in the program field, Instead save the script as a .ps1 file and pass the script file with fully qualified path as a parameter in the parameter field.

Typically, the following should be added to the parameter field:

-noninteractive –nologo -ExecutionPolicy Bypass -command "& 'c:\datafiles\cleanup.ps1'"

Needless to mention that the progrm / script field shall contain the PowerShell executable with its fully qualified path, which will be like this:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
You may also want to have a look at the clean up script on the TechNet site, which has many more capabilities, like crating a log of files deleted and so on.