We had a client who needed to delete their aged IIS log files without human intervention. To do this requires two steps:
1 – Script To Delete Files Older Than X Days
In the example below we are deleting from C:\inetpub\logs\LogFiles\W3SVC1
that have not been modified for more than 90 days:
ForFiles /p C:\inetpub\logs\LogFiles\W3SVC1 /s /d -90 /c "cmd /c del @file"
Note that you may need to put single or double quotes around your path but as you can see we did not.
/P = the path
/S = include subfolders
/D = MODIFIED Date (i.e. not necessarily creation date)
-90 = take 90 days off the Modified Date to include it in this filter
You can obviously adjust this to fit your requirements.
2 – How To Schedule A Task To Run When Any User Logs On
We wanted to avoid having to create a new local or domain user to run this script under because it is just one more account to reset the password on and just one more increase in the attack surface area. So we decided to have it run any time ANYONE logs on to that server and there are a couple of small quirks to make this work:
CLICK TO EXPAND GRAPHICS
- Launch the TASK SCHEDULER
- Right click on TASK SCHEDULER LIBRARY and select CREATE TASK
- On the GENERAL tab:
- Type a NAME
- Click CHANGE USER OR GROUPS button
- Type
USERS
and click OK
- Type
- On the TRIGGERS tab click the NEW button
- Change the BEGIN THE TASK drop down to AT LOG ON
- Ensure SETTINGS are at ANY USER
- Click OK
- On the ACTIONS tab click the NEW button
- Set the ACTIONS drop down to START A PROGRAM
- type FORFILES in the PROGRAM/SCRIPT field
- type the rest of your ForFiles delete command in the ADD ARGUMENTS field
- In our case that is:
/p C:\inetpub\logs\LogFiles\W3SVC1 /s /d -90 /c "cmd /c del @file"
- In our case that is:
- Click OK and have a nice day
- Actually, you should log off then log back in to confirm the script is working
- If it works TASK SCHEDULER will show the LAST RUN RESULT as THIS OPERATION COMPLETED SUCCESSFULLY (0x0)
- Any other description means you have a problem to fix
0 Comments