65.9K
CodeProject is changing. Read more.
Home

SCRIPT Clear all TEMP Files and Folders

starIconstarIconstarIconstarIconstarIcon

5.00/5 (4 votes)

Dec 9, 2016

Ms-PL

2 min read

viewsIcon

46920

SCRIPT Clear all TEMP Files and Folders

Left unattended, your disk space can quickly fill up with junk, thanks to temporary files and folders (some even very large ones). In this article, I give you a quick and easy script to clear your temp files and folders.

Locations of Your Temporary Files

Thankfully, you do not have to remember complicated paths and changed locations of temporary folders for your computer yourself and any other user accounts that may be running concurrently (like service accounts). Instead, you can use simple environment variables: %TMP% and %TEMP%. You will also have temporary files in: “%WINDIR%\Temp”, “%USERPROFILE%\Local Settings\Temp” and “%LOCALAPPDATA%\Temp” folders.

The Command

The command to delete is rather straight forward: DEL /S /Q “<PATH>”. Copy and paste the below into a Notepad window:

DEL /S /Q "%TMP%\*.*"
DEL /S /Q "%TEMP%\*.*"
DEL /S /Q "%WINDIR%\Temp\*.*"
DEL /S /Q "%USERPROFILE%\Local Settings\Temp\*.*"
DEL /S /Q "%LOCALAPPDATA%\Temp\*.*"

Save the above Notepad file as “ClearTemp.cmd” (File > Save As, change the filter from “Text files” to “All files” and then provide the file name). Now right click on the file you saved and run it with elevated rights (Run as Administrator). You will see a command window pop up, a string of output running through and then the window will disappear.

Caveats

  • The above script will not delete files that are currently open (say a program is keeping a file open and locked, that file will not be deleted).
  • If you are currently downloading something or have an installation in progress, those programs will place data temporarily in the TEMP folders and some or all of this data will get deleted. This will cause problems with the download or installation. So, ensure that no downloads or installations are in progress before running the command.

You can automate this by placing the command in your Windows Registry under the Run key so that it is run at every system startup. Note that if you place it at the HKEY_LOCAL_MACHINE’s Run key, then, you will need to remove the “%USERPROFILE%” temp path from the command. Similarly, if you place it in HKEY_CURRENT_USER (your own) Run key, then you will need to have Administrator rights by default or many files will not be deleted — you will not be prompted, those files will remain as they are.