Does the bat file know its name and can it delete itself

At some point in my script, I would like the bat script to delete itself. This requires the script to know its name and then use that name to delete itself. Is it possible?

+5
source share
5 answers

None of the existing answers provides a clean way for the batch file to delete itself and exit without a visible error message.

Just inclusion del "%~f0"deletes the script, but also leads to the ugly "Batch file cannot be found." error message.

If OK for the script to close the parent CMD process (console window), then the following works fine without an error message:

del "%~f0"&exit

, , script CMD- .

1. , , . EXIT /B, , , , , script , STARTed .

start /b "" cmd /c del "%~f0"&exit /b

2. , , , CALL stderr nul.

>"%~f0.bat" echo del "%~f0" "%~f0.bat"
2>nul "%~f0.bat"
+11

,% 0 , .

+3

:

del %0
exit
+2

% 0 , bat. ,

mybats\delyourself.bat tango roger

% 0 mybats\delyourself.bat

del %0 , .

%~f0 exapnds .

+1

, , , no errorLevel 1. : DeleteMyself.cmd:

START CMD /C DEL DeleteMyself.cmd

, DeleteMyself.cmd errorLevel 0. TestDeleteMyself.cmd:

call DeleteMyself.cmd
echo Errorlevel: %errorLevel%
-1

All Articles