how to get a windows batch file to update itself safely

In order to do that, the following requirements must be satisfied:

  • The overwrite of the Batch file for the newer version of itself must be the last command of the Batch file, so the next command after the copy must be an exit /B or exit.
  • Previous commands must be loaded in memory before they are executed. This is easily done by enclosing them in parentheses.

That is:

@echo off
rem Do program business here...
echo Anything

rem Parse/load following commands before execute they:
(
rem Copy many files, probably a newer version of myself
xcopy /Y *.*
rem You may execute other commands here...
echo Files copied!
rem Terminate *this version* of the running Batch file
exit /B
)

@ECHO OFF
SETLOCAL
IF /i NOT "%~dp0"=="%temp%\" (
 COPY /y "%~dpnx0" "%temp%\%~nx0" >nul
 "%temp%\%~nx0"

)
ECHO Now we run the rest of the original UPGRADE.BAT

This sequence of lines at the start of upgrade.bat should work.

See whether we're running from a copy in %temp%. If not, then copy this file to temp & run it from there.

Hence the batch actually runs from %temp% and the original version may be overwritten.

Tags:

Batch File