How to make .BAT file delete it self after completion? I have a simple bat file that terminates a process. I want that .BAT file to delete itself.
The Merlyn Morgan-Graham answer manages to delete the running batch script, but it generates the following error message: "The batch file cannot be found." This is not a problem if the console window closes when the script terminates, as the message will flash by so fast that no one will see it. But the error message is very undesirable if the console remains open after script termination.
John Faminella has the right idea that another process is needed to cleanly delete the batch file without error. Scheduling a task can work, but there is a simpler way: use START to launch a new delete process within the same console. It takes time for the process to initiate and execute, so the parent script has a chance to terminate cleanly before the delete happens.
start /b "" cmd /c del "%~f0"&exit /b
Update 2015-07-16
I've discovered another really slick way to have a batch script delete itself without generating any error message. The technique depends on a newly discovered behavior of GOTO (discovered by some Russians), described in English at http://www.dostips.com/forum/viewtopic.php?f=3&t=6491
In summary, (GOTO) 2>NUL behaves like EXIT /B, except it allows execution of concatenated commands in the context of the caller!
So all you need is
(goto) 2>nul & del "%~f0"
#ECHO OFF
SETLOCAL
SET someOtherProgram=SomeOtherProgram.exe
TASKKILL /IM "%someOtherProgram%"
ECHO "This script will now self-destruct. Please ignore the next error message"
DEL "%~f0"
Note that the DEL line better be the last thing you intend to execute inside the batch file, otherwise you're out of luck :)
This will print out an ugly error message, but it is benign, and the code is slightly less confusing this way. If you care a lot about getting rid of the error message, see dbenham's answer to get rid of it.
You didn't mention the OS, but if this is on Windows XP Professional and you have the appropriate permissions, you can have the batch file schedule a one-shot Windows Scheduled Task to delete the file at a later time. Use the schtasks command, documented here.
Otherwise, you typically can't delete a file that is being executed, since that has the potential for all sorts of nastiness. Additionally, trying to delete an executable in use is viewed as very suspicious behavior by any number of antivirus programs, so it's likely that you would run afoul of these as well.
Just add this command at the last line of your batch file
Del batch_file_name.bat
batch_file_name.bat is the name of your batch file
Cheers
you could do #Merlyn's aswer
#ECHO OFF
SETLOCAL
SET someOtherProgram=SomeOtherProgram.exe
TASKKILL /IM "%someOtherProgram%"
DEL "%~f0"
Now make a vbscript with this coding and save it as hidden.vbs, this vbscript will hide the batch file's window.
set w = CreateObject(“WScript.Shell”)
W.Run chr(34) & “%userprofile%\desktop\the_batch_file.bat” & chr(34), 0
set w= Nothing
Then have the batch file run this vbscript
#ECHO OFF
SETLOCAL
SET someOtherProgram=SomeOtherProgram.exe
TASKKILL /IM "%someOtherProgram%"
start "path to hidden.vbs"
DEL "%~f0"
This will hide the batch file before deleting it making the error message impossible to see.
Inline next command to do the "last things" as ghost self. It can be the exit command or some other things before exiting.
#echo off
del "%~f0" && echo All's done. I must exit! && pause > nul && exit
You could also direct the output of the DEL "%~f0" to NULL output like so...
#ECHO OFF
SETLOCAL
SET someOtherProgram=SomeOtherProgram.exe
TASKKILL /IM "%someOtherProgram%"
DEL "%~f0" > NUL
Related
How can I write a batch file that runs cmd.exe, enters the partial command robocopy then waits for user input to complete and execute the robocopy command? It seems like it should be the simplest thing to do but no method I've tried enters the command in such a way as to hold and wait for user input and then successfully execute the completed robocopy command
For example:
#echo off
set var="robocopy "
cmd.exe %var%
appears to work but then, for example, user-inputting /? to bring up robocopy's info instead brings up cmd.exe's info
Another example:
#echo off
cmd /k robocopy
Runs robocopy with no destination/source folders or switches, then closes robocopy and waits for a new user-inputted command.
what I'm trying to do is have a batch file that when I click it a cmd window will open with the partial command robocopy already entered ready for me to complete the command with source/destination/switches and execute it with an enter key press - I use robocopy all day long so this would be a big time saver.
it's not possible in the way you seem to think. That would mean to mess with the keyboard buffer (was pretty common with the C64 back in those times, but it's not possible in (pure) batch).
But the following should give you a good start for automation. It assumes, you use the same parameters each time and just want to give it a source and a destination folder. Adjust to your needs (especially the params - I added /L to prevent it from unwanted actions while testing):
#echo off
set "command=robocopy"
set "params=/L /E /MOV /MT:12 /FP /log+:robocopy.log /TEE"
set /p "source=Enter Source: "
set /p "destin=Enter Destination: "
%command% "%source%" "%destin%" %params%
The cmd.exe or cmd.exe /k isn't necessary, until you want robocopy to work in a new window.
I made a Main batch file with the lines below:
#echo off
color 1e
title ------ Just a Test ------
start "C:\Users\%USERNAME%\Desktop\Check.bat"
:START
echo Welcome to the Game!
...
And Check.bat contains:
#echo off
if not exist "C:\Users\%USERNAME%\Desktop\Batch_System\importantFile.dll" goto ERROR
if exist "C:\Users\%USERNAME%\Desktop\Batch_System\importantFile.dll" goto CONTINUE
:ERROR
cls
echo ERROR :
echo Important file not found. please reinstall the program
pause
exit /b
:CONTINUE
cls
exit /b
When I use the command start, it starts only a command prompt with the Check.bat directory and the main batch file continues executing the game. I want to force close the main batch file if importantFile.dll doesn't exist.
Okay, let me explain: When the main batch file is executed and runs the command start to start another batch file called Check.bat, the file Check.bat checks if the file importantFile.dll exists, and if not, Check.bat displays an error message.
Does anyone know how to write Check.bat in a manner that when the .dll file does not exist, force the main batch file to exit?
First, help on every command can be get by running in a command prompt window the command with /? as parameter. start /? outputs the help of command START. call /? outputs the help of command CALL usually used to run a batch file from within a batch file. Those two commands can be used to run a batch file as explained in detail in answer on How to call a batch file that is one level up from the current directory?
Second, the command line
start "C:\Users\%USERNAME%\Desktop\Check.bat"
starts a new command process in foreground with a console window with full qualified batch file name as window title displayed in title bar at top of the console window. That is obviously not wanted by you.
Third, the Wikipedia article Windows Environment Variables lists the predefined environment variables on Windows and their default values depending on version of Windows.
In general it is better to use "%USERPROFILE%\Desktop" instead of "C:\Users\%USERNAME%\Desktop".
There is no C:\Users on Windows prior Windows Vista and Windows Server 2008 by default at all.
The users profile directory can be on a different drive than drive C:.
It is also possible that just the current user's profile directory is not in C:\Users, for example on a Windows server on which many users can logon directly and for which the server administrator decided to have the users' profile directories on a different drive than system drive making backup and cleaning operations on server much easier and is also better for security.
Well, it is also possible to have the user's desktop folder not in the user's profile directory. But that is really, really uncommon.
Fourth, on shipping a set of batch files, it is recommended to use %~dp0 to call other batch files from within a batch file because of this string referencing drive and path of argument 0 expands to full path of currently executed batch file.
The batch file path referenced with %~dp0 always ends with a backslash. Therefore concatenate %~dp0 always without an additional backslash with another batch file name, folder or file name.
See also What is the reason for batch file path referenced with %~dp0 sometimes changes on changing directory?
Fifth, I suggest following for your two batch files:
Main.bat:
#echo off
color 1e
title ------ Just a Test ------
call "%~dp0Check.bat" || color && exit /B
echo Welcome to the Game!
Check.bat:
#echo off
cls
if exist "%~dp0Batch_System\importantFile.dll" exit /B 0
echo ERROR:
echo Important file not found. Please reinstall the program.
echo/
pause
exit /B 1
The batch file Check.bat is exited explicitly on important file existing with returning exit code 0 to the parent batch file Main.bat. For that reason Windows command processor continues execution of Main.bat on the command line below the command line calling the batch file Check.bat.
Otherwise Check.bat outputs an error message, waits for a pressed key by the user and exits explicitly with non zero exit code 1. The non zero exit code results in Main.bat in executing the next command after || which is COLOR to restore initial colors and next executing also EXIT with option /B to exit the execution of Main.bat.
See also:
Single line with multiple commands using Windows batch file
What are the ERRORLEVEL values set by internal cmd.exe commands?
Which cmd.exe internal commands clear the ERRORLEVEL to 0 upon success?
Where does GOTO :EOF return to?
exit /B without an additionally specified exit code is like goto :EOF.
The CALL command line in Main.bat could be also written as:
call "%~dp0Check.bat" || ( color & exit /B )
And Main.bat could be also written as:
#echo off
color 1e
title ------ Just a Test ------
call "%~dp0Check.bat"
if errorlevel 1 (
color
goto :EOF
)
echo Welcome to the Game!
I do not recommend using in Main.bat just EXIT instead of exit /B or goto :EOF. Just EXIT would result in exiting the current command process independent on calling hierarchy and independent on how the command process was started: with option /K to keep it running to see error messages like on opening a command prompt window and next running a batch file from within command prompt window, or with /C to close the command process after application/command/script execution finished like on double clicking on a batch file.
It is advisable to test batch files by running them from within an opened command prompt window instead of double clicking on them to see error messages on syntax errors output by cmd.exe. For that reason usage of just EXIT is counter-productive for a batch file in development. Run cmd /? in a command prompt window for help on Windows command processor itself.
Last but not least see:
Microsoft's command-line reference
SS64.com - A-Z index of the Windows CMD command line
start is asynchronous by default. Use start /wait so that main.bat can test the exit code of check.bat. Make check.bat return an appropriate exit code.
For example...
main.bat
#echo off
start /b /wait check.bat
if not %errorlevel% == 0 exit /b
echo "Welcome to the game!"
...
check.bat
#echo off
if exist "importantfile.dll" exit 0
echo ERROR: Important file not found. Please reinstall the program.
pause
exit 1
notes
Added /b to start to avoid opening another window. Change that per your preference.
You could use call instead of start but call gives the called code access to the variables of main.bat so encapsulation is improved if you use start as you did.
The logic in check.bat is simplified above. Once you identify the success path early in the script and exit, the rest of the script can assume the fail path. This saves you a few if's and labels which you might find simplifies writing and reading of similar scripts. Beware of potentially confusing multiple exit points in longer scripts though!
When choosing exit codes, 0 is a common convention for success.
The above code is just one technique - there are several other options (such as checksomething && dosomethingifok). Some useful information on return codes, and checking them, can be found in http://steve-jansen.github.io/guides/windows-batch-scripting/part-3-return-codes.html
Thanks to the answer from Mofi. I've my example and exp. on this. To be short, it's about the setting of log date format. You may change the format of time , date and log. you may have the result.
why-batch-file-run-with-failure-in-windows-server
Thanks. Thought I'd try writing a batch file to kill another open cmd session that is constantly open churning out lots of scrolling info.
I got a bit carried away and am now outta my league so to speak.
Basically I am trying to search for "£000.00" within a each emerging line of tet that appears in the other running open command window. The running command session is named in the window as C:\windows\system32\cmd.exe but is does have a valid .exe process name in task manager while running and open.
The batch file code below is as far as I've got.
The idea is that when the above string is found in the other process that process/program get closed down them re-launched.
This is as far as I've got.
#echo off
#echo off
title Shut down other process and relaunch
:loop
start /d "C:\Users\Desktop" ActiveDOSprogram.exe
:: #setlocal enabledelayedexpansion
:: #echo off
:: set stringfound=1
find /c "*£000.00*" C:\Windows\system32\cmd.exe && (echo found %date% %time%:~0,-3% >> "%USERPROFILE%\Desktop\Crash_Report.txt"
taskkill /IM ActiveDOSprogram.exe /F
timeout /t 20
start /d "C:\Users\Desktop" ActiveDOSprogram.exe
goto loop
So when I tried this without any variables and in a loop and I think i nearly blew my PC!
Reason I'm stuck is I'm really a novice at this (but trying) and I got as far as I think I need a variable in there somewhere, that only move's to the next line (taskkill+restart) when £000.00 is found in the other process.
Thanks
wingman
So now i have 2 .bat files. one copies some file if it was updated ( robocopy C:\location C:\destination) and another one that executes a some kind of .exe file (start c:\BAT\fraps.exe) , now what i need is maybe a one file, so that WHEN a file was copied using "robocopy" the executive file would run automaticaly. So maybe there is a way to merge them into one or smth.
Errorlevels are set by robocopy: errorlevel 1 means that a file was successfully copied.
robocopy C:\location C:\destination
if errorlevel 1 if not errorlevel 2 start c:\BAT\fraps.exe
Here is proof of concept code - following extended comments:
#echo off
md test1
:loop
>test1\testfile.txt echo aaa
robocopy test1 test2
if errorlevel 1 if not errorlevel 2 pause
del test1\testfile.txt
goto :loop
Use /WAIT option, when the application is stared then it will wait until it terminates.
Use /B option, when application is started then it will not create a new window.
Example:
start /wait Command CALL D:\YourFirstScript.bat
start /wait program.exe
start /wait Command CALL X:\YourSecondScript.bat
It's a good idea to print a message before and after.
Example:
ECHO Starting program.
start /wait program.exe
ECHO Finished.
See below link for more details.
How do I launch multiple batch files from one batch file with dependency?
Note: When you run script as administrator then you need to set full path as the default is set to "C:\Windows\System32".
The easiest way to set is
start %~dp0Directory\program.exe
See for details about "%~dp0" here
What does %~dp0 mean, and how does it work?
This is my first post and I hope that this will help you.
i need to make a batch that looks for file
and once it exist it will run a windows cmd batch
i tried the below code but its not working
#ECHO off
IF EXIST C:\file.txt CALL batch.cmd
I interpret "and once it exist..." as "keep looking and as soon as the file exists...". Use a loop:
#echo off
look:
timeout 1 >nul
IF NOT EXIST C:\file.txt goto :look
call batch.cmd
Note: never run a loop without a delay (timeout here) to avoid high CPU load)
If you like to write code all in a line, you should do it like this
#ECHO off & IF EXIST C:\file.txt CALL batch.cmd