At some point in my script, I'd like the bat script to delete itself. This requires that the script know its name and then to use that name to delete itself. Is this possible?
You can just make it delete itself with del uninstaller. bat or del "%~f0" , where %~f0 represents the full path of the script.
Batch file does delete files.
You can create a batch program that calls itself. However, you must provide an exit condition.
Ctrl+C. One of the most universal methods of aborting a batch file, command, or another program while it's running is to press and hold Ctrl + C .
None of the existing answers provide a clean way for a batch file to delete itself and exit without any visible error message.
Simply including del "%~f0"
does delete the script, but it also results in an ugly "The batch file cannot be found." error message.
If it is OK for the script to close the parent CMD process (the console window), then the following works fine without any error message:
del "%~f0"&exit
But it is a bit more complicated if you want the script to delete itself and exit without closing the parent CMD process, and without any error message.
Method 1: Start a second process that runs within the same console window that actually performs the delete. The EXIT /B
is probably not necessary, but I put it in to maximize the probability that the batch script will close before the STARTed process attempts to delete the file.
start /b "" cmd /c del "%~f0"&exit /b
Method 2: Create and transfer control to another temp batch file that deletes itself as well as the caller, but don't use CALL, and redirect stderr to nul.
>"%~f0.bat" echo del "%~f0" "%~f0.bat"
2>nul "%~f0.bat"
If I'm not mistaken, %0 will be the path used to call the batch file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With