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

前端 未结 5 537
失恋的感觉
失恋的感觉 2020-12-07 02:37

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 possib

相关标签:
5条回答
  • 2020-12-07 03:01

    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"
    
    0 讨论(0)
  • 2020-12-07 03:01

    %0 gives you the relative path the from the directory where the bat file was started. So if you call it

    mybats\delyourself.bat tango roger
    

    %0 will contain mybats\delyourself.bat

    del %0 works if you haven't changed your current directory.

    %~f0 exapnds to the full path to the file.

    0 讨论(0)
  • 2020-12-07 03:15

    If I'm not mistaken, %0 will be the path used to call the batch file.

    0 讨论(0)
  • 2020-12-07 03:16

    For me it was important, that I have no errorLevel 1 after I exited the batch file. I found an suitable and easy answer this way: DeleteMyself.cmd:

    START CMD /C DEL DeleteMyself.cmd
    

    Test batch if DeleteMyself.cmd is returning errorLevel 0. TestDeleteMyself.cmd:

    call DeleteMyself.cmd
    echo Errorlevel: %errorLevel%
    
    0 讨论(0)
  • 2020-12-07 03:20

    Tested and working:

    del %0
    exit
    
    0 讨论(0)
提交回复
热议问题