Sign in with
Sign up | Sign in
Your question
Solved

How to get a batch script to delete itself on exit?

Tags:
  • DOS Batch
  • Command Prompt
  • Windows 7
Last response: in Windows 7
Share
October 4, 2014 8:55:46 AM

I am attempting to create a script that will assist in select software installation from a large pool of software on newly imaged PCs. I have the script itself done, but the issue is is requires a flash drive to run, and those are in short supply, especially when doing multiple PCs at once. I created a script to copy the resource files needed to run the main batch script to %TEMP%\MyScript so I can run locally and not off of the flash drive, but I am having difficulty with the cleanup. A cleanup script runs (From %TEMP% that removes the %TEMP\MyScript successfully, but when deleting itself, the script errors out and returns to CMD.

Here are the commands I am using

<--OUTPUT REMOVED-->
ECHO ======= PRESS ANY KEY TO EXIT =======
PAUSE > NUL
START %TEMP%\CleanUp.bat

At this point CleanUp.bat runs:
@ECHO OFF
ECHO Cleaning up install files...
ECHO.
ECHO Removing desktop shorcut...
DEL "%USERPROFILE%\Desktop\Link to Software Installer.lnk" > NUL
ECHO.
ECHO Removing %TEMP%\MyScript
RMDIR /S /Q %TEMP%\MyScript\
ECHO.
ECHO Removing CleanUp utility...
REM Delete self on Exit
DEL /f/q "%~0" | exit

After the Removing CleanUp Ultility... text shows, it then reads "The Batch File cannot be found." and returns to CMD in the %TEMP% location. Everything is removed, but I need the script to exit and close the CMD window.

More about : batch script delete exit

Best solution

a b $ Windows 7
October 4, 2014 9:20:14 AM

Hello... I believe you need to try EXIT or EXIT /b will end the batch file. http://en.wikibooks.org/wiki/Windows_Batch_Scripting
Share
October 5, 2014 12:56:18 PM

Ironsounds said:
Hello... I believe you need to try EXIT or EXIT /b will end the batch file. http://en.wikibooks.org/wiki/Windows_Batch_Scripting


This works to prevent the error, but still leaves the CMD window open. After more searching and playing, I have the following code that deletes the cleanup script (CleanUp.bat) and closes the CMD window:
  1. START /b "" cmd /c DEL "%TEMP%\CleanUp.bat" && EXIT

The full cleanup script is:
  1. @ECHO OFF
  2. ECHO Cleaning up install files...
  3. ECHO.
  4. ECHO Removing desktop shorcut...
  5. DEL "%USERPROFILE%\Desktop\Link to Software Installer.lnk" > NUL
  6. ECHO.
  7. ECHO Removing %TEMP%\MyScript
  8. RMDIR /S /Q %TEMP%\MyScript\
  9. ECHO.
  10. ECHO Removing CleanUp utility...
  11. REM Delete self on Exit
  12. START /b "" cmd /c DEL "%TEMP%\CleanUp.bat" && EXIT
m
0
l
!