Powershell Delete Files After X Days and Keep Log

I have been managing a project to develop a simple app to upload files to a web server. In order to do this with the way we were managing state, we had to temporarily store the file on the server until submit. This posed a problem with files that were put in temp, but then the browser closed. Since the browser closed didn’t cleanup the file I had to write a script to do that. I thought I’d share it.

This script has the -whatif flag in it. That means you can run it and it will simulate what it would do and will tell what would have happened. When you get it set for your environment just take -whatif out, but be careful in doing so.

One nice feature of this script is that it will self clean the log files based on the number of days you tell it to delete. In my case I clean it out every day, so I only keep one log file.

#####################################################
#Checks to see if $files contains information, if it does not, then the script is finished
#$files stores all items in the directory and subdirectories where the last modified date is less than x days and is not a #folder
#if $files contains info then the script starts a log and removes all files that are stored in $files
#the logs are self cleaning because they are stored in the directory being checked and will be deleted as any other file
#add –whatif after –verbose in the foreach statement to test with no destructive action
#Andrew Alaniz – 6/8/2011
#####################################################
if($files = get-childitem D:Location -recurse | where {$_.lastwritetime -lt (get-dateM).adddays(-1) -and -not $_.psiscontainer}){
start-transcript D:Location$(get-date -format MMddyyHH).txt
foreach ($file in $files){%{remove-item $file.fullname -force -verbose -whatif}}
stop-transcript}

To execute this script just setup a scheduled tasks. This batch file will execute the powershell script. You just use the scheduled task to execute the batch file.

powershell -command “& ‘D:ScriptsDeleteOldFiles.ps1’ “

One thought on “Powershell Delete Files After X Days and Keep Log


Leave a Reply

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

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.