Clean up windows TEMP automatically.


What, one more solution to "clean temp" on windows? YES!

There are a lot of examples for cleaning up temp. Forfiles is often mentioned, but forfiles fails on quite some occasions: Special characters in file-name, folders starting with tilde character, and so on. I wasted quite some time on that.

My solution requires SED and TAIL from UnixUtil, preferably in your PATH.
It does a very simple approach: list the directory sorted by newest first, and only keep the first ten newest entries. This also works around some programs which use that directory to store things for "Jobs to do after next reboot or logon".
It is designed to be put into your autostart folder, either directly if the UnixTools are in your path, or as a shortcut.
Using %temp%\..\temp is a security measurement. If some program messed up my environment, the batch will still only clean up a directory actually named "temp" and not anything else.

cd /d %temp%
dir %temp%\..\temp /o-d /a /b | tail +10 | sed -e "s/^/rd\ \/s\ \/q\ \"\.\.\\temp\\/" -e "s/$/\"/" > %temp%\deltemp.cmd
dir %temp%\..\temp /o-d /a /b | tail +10 | sed -e "s/^/del\ \/q\ \"\.\.\\temp\\/" -e "s/$/\"/" >> %temp%\deltemp.cmd
call %temp%\deltemp.cmd
del /q %temp%\deltemp.cmd

Instead of you making the .cmd you can alternativelydownload it.

You can easily extend it to clean up %WINDIR%\temp too.

Legal Stuff: This is a private homepage. All "TM" mentioned here belong to their owners and not me. Anyone offended contact me at email-address.