Windows cannot remove a directory which is your current working directory, so the best way to empty a directory is to make it your current directory before trying to remove it. This will essentially remove all permissible content without touching the directory itself. (Note: All content may not be removed, just those which aren't locked/in use, and which you have sufficient permissions to remove).
@Echo Off
SetLocal EnableExtensions
Rem If the directory to empty, has no file content, end the script.
"%__APPDIR__%where.exe" /Q /R "%TEMP%" * || (
Echo %TEMP% has no file content.
Echo Exiting . . .
"%__APPDIR__%timeout.exe" /T 3 /NoBreak 1> NUL
GoTo :EOF
)
Rem If the running script is in within, the directory to empty, end it.
SetLocal EnableDelayedExpansion
If /I Not "!__CD__:%TEMP%=!" == "%__CD__%" (
Echo Cannot empty %TEMP% because this script is located within it.
Echo Please move %~f0 to another location and try again.
Echo Press any key to exit . . .
"%__APPDIR__%timeout.exe" /T -1 1> NUL
GoTo :EOF
)
EndLocal
Rem Make the directory to empty, the current working directory.
Rem If the directory to empty, cannot be found, end the script.
PushD "%TEMP%" 2> NUL || (
Echo The directory assigned to %%TEMP%% cannot be found.
Echo Exiting . . .
"%__APPDIR__%timeout.exe" /T 3 /NoBreak 1> NUL
GoTo :EOF
)
Rem If the end user answers N, or n, end the script.
"%__APPDIR__%choice.exe" /M "Are you sure you want to empty your Temp directory"
If ErrorLevel 2 (
Echo Exiting . . .
"%__APPDIR__%timeout.exe" /T 3 /NoBreak 1> NUL
GoTo :EOF
)
Rem Empty permissible content from the current directory.
RD /S /Q . 2> NUL
Title Cleaned %CD%.
Echo Emptied permissible content from %CD%
Rem Make the previously current directory, current again.
PopD
Echo Press any key to exit . . .
"%__APPDIR__%timeout.exe" /T -1 1> NUL
GoTo :EOF
The code above may have more content than the other answers, but it shows a logical progression you should try to follow when creating your scripts, especially those which are removing file and directory content.
If you do not want a well thought out structure to your code then you could just do it like this:
@CD /D "%TEMP%" 2>NUL||Exit /B
@"%__APPDIR__%choice.exe" /M "Are you sure you want to empty your Temp directory"
@If ErrorLevel 2 Exit /B
@RD /S /Q . 2>NUL
@Title Cleaned %CD%.
@Echo Emptied permissible content from %CD%
@"%__APPDIR__%timeout.exe" /T 2 1>NUL