Safely modify batch file while running - windows

I'm implementing a batch file similar to the Gradle wrapper. The idea is that it will download the main application and run it, without the user having to download and install the application itself.
This is all working fine, and now I'm implementing updating the application. This involves replacing the batch file with a new version of the batch file (which has a new download URL in it, in addition to any changes to the batch file itself).
However, when my application replaces the batch file, this leads to weird results (as discussed in https://stackoverflow.com/a/31257641/1668119 and other answers in that question). Is there a safe way to replace a batch file while it is running that doesn't result in new or removed lines causing issues?

Based on Mofi's comment and the answer they linked to, I'm using something like this:
setlocal EnableDelayedExpansion
my-application && exit 0 || exit !ERRORLEVEL!
The batch file executor seems to read the file one line at the time, so always exiting on that line means it will never try to read anything more from the batch file and so it doesn't matter if the batch file has been modified.
setlocal EnabledDelayedExpansion is important as otherwise ERRORLEVEL is evaluated before the application is run and so the script always returns 0 even if the application fails.

Related

Visual Studio Post Build Event if exists

I want to call a batch file in my post build step in Visual Studio. Locally the batch file exists, just the command
call "$(SolutionDir)PostBuildSen.bat" "$(TargetDir)" "$(TargetName)"
correctly calls and executes the batch file.
However when I want to check if the batch file exists first (since others will use the same Post Build Event), I get the error
:VCEnd" exited with code 255.
The command is
if exists "$(SolutionDir)PostBuildSen.bat" call "$(SolutionDir)PostBuildSen.bat" "$(TargetDir)" "$(TargetName)"
The Diagnostic output tells me
2> Done executing task "Exec" -- FAILED.
How do you handle this?
The Solution Directory contains a folder with an underscore, i.e. \Dev_Main\ and I have read that for the batch file that is to be called at least that doesn't work. However I am not sure if that is the issue with folders as well and how to cope with it. Also, since the call command works, I am not sure this is the problem.
Furthermore, if I replace the call with cmd /C, the exit code is 1 and the (minmal) output tells me
1>The filename, directory name, or volume label syntax is incorrect.
Also, I will add this as a custom command to a CMakeLists file later on, so the solution needs to work with that.
Thanks to Hans Passant's comment, I solved the problem. The query for the file needs to be if exist rather than if exists.

Build output from Visual Studio 2010 external tools in output window

I run a batch file as an external tool (by adding it in Tools->External tools) in VS2010 (I've checked the "Use Output Window" option). This batch file performs compilation as in VS command prompt. The project that I'm working on has makefiles for various folders, so I use the mk command to build.
In the batch file, I set up the VS environment and then run the following commands:
cd $directoryWhichContainsFileToBuild
mk
cd main //This directory contains the executable that is to be built
mk
I see the output of the first mk in the Output window but after that it just hangs. I also tried to use an echo after the first mk but even that doesn't get printed in the output window (the ones before it can be seen).
Somewhere I read that there is an issue with VS 2010 output window where it hangs after showing some output, although I couldn't really be sure that that is what's the issue here.
Do I need to enable some other VS setting? Has anybody else encountered this issue?
Thanks.
Update: I unchecked the "Use Output Window" and "Close on exit" option, and I see an extra statement: "Press any key to continue". On doing that however, their is no further processing of the batch file.
Update2: Got it to work by prefixing mk with "call".
Thanks all who tried.
It is always good in batch files to specify executables with full path and file extension instead of just the file name. This avoids often lots of problems.
Here was just mk used instead of mk.bat. Therefore on every compile the command line processor cmd.exe searches for mk.* and then checks if any of the found files have an extension listed in environment variable PATHEXT. The order of file extensions separated by a semicolon in PATHEXT defines the order of execution in case of a directory contains multiple mk.* files.
If a command being specified in a batch file not being an internal command of cmd.exe without path, command line processor searches first for a file with given name in current working directory. This is often one more cause of error. What is the current working directory on execution of the batch file?
Next if no file to execute can be found in current working directory, the command line processor searches in all folders being listed in environment variable PATH separated by semicolons.
So specifying in batch files edited only rarely an external application or another batch file with full path, file name and file extension, in double quotes if necessary because of 1 or more spaces in path or file name, helps command line processor to more quickly execute that application or batch file and avoids problems because of executable not found (unknown command).
Sure, when typing commands in a command prompt window, nobody wants to enter the executables with full path, name and extension. But for batch files it is always good to be not lazy and type files to be executed with full path and extension.
TripeHound has given already the explanation why the observed behavior occurred here.
If a batch file is executed from another batch file without using command call, the command line processor continues batch execution in the other batch file and does never come back. In a C/C++ program this is like using goto with the difference that parameters can be passed to the batch file containing the further commands to be executed next.
But running from within a batch file another batch file with call results in continuation of execution below the line calling the other batch file once the other batch file reaches end, except command exit is used in the called batch file without parameter /B.
So the solution here is using:
cd /D "Directory\Which\Contains\File\To\Build"
call "Path\Containing\Batch\File\To\Build\mk.bat"
rem With mk.bat not changing current working directory change working
rem directory to the directory containing the executable to be built.
cd main
call "Path\Containing\Batch\File\To\Build\mk.bat"
BTW: exit exits command processor, exit /B exits just current batch file. I'll give you three guesses why the parameter is B and not a different letter. Yes, B is the first letter of batch.
Writing as a separate answer instead of an update in the question itself as many readers see the header and skim to the answer: got it to work by prefixing mk with "call". (#TripleHound has also posted the conceptual reason for it in the comment above.)

Task Scheduled not running batch file

I have file which does somethings and it works fine if I run the file manually but it doesn't run when set up in task scheduler.
Batch file is in a folder on desktop on windows 7.
Any feedback will be helpful.
I've even tried this link solution didn't work.
Most likely in this case you need to make sure that the directory the script runs in ("Start in") is set correctly. Usually this is the same directory that contains your script. You can set this in the Scheduled Task's properties.
As a test, try moving the .bat file to a directory with basic permissions (maybe a shared directory for example).
I had the same problem as you. My .bat file was located in a folder with some restrictive permissions on it, so that only my user account could access it. Even though I had set up the task scheduler to use my credentials it still failed. Moving the .bat file to another directory sorted the issue.
I don't know if this will help, but in bashing my head against one problem after another for far too many hours, I finally got my own batch file to work properly as a scheduled task. Some of the things I learned in the process:
If you are the user who has created the scheduled task, you must also be a user who has logged into the system using a password.
Any reference to a file name, inside the batch file, needs to be the last part of fully qualified path, starting with drive letter.
If you do a comparison, like [%flag%] EQU [0], be aware that the "[" and "]" symbols are string literals that are included in the data that gets compared.
If part of your batch file sets a variable and includes a "FOR" loop that calls a subroutine in which you expect to change the variable, you need to make sure that the variable is originally initialized as early as possible in the batch file. That is, something like this:
IF ... (
SET %flag=0
FOR ... (CALL :subr)
IF [%flag%] EQU [1] ( main scheduled-task command goes here)
)
GOTO :eof
:subr
IF ... (SET %flag=1)
:eof
--worked from the command line, but not as a Scheduled Task. I had to move the initialization of %flag to be done before that very-first IF.

Self executing delete files

How would I create a self executing batch file to delete files in a specific folder.
Scenario: I have a folder on a server where all the scannered documents go to once they have been scanned. They want a the scanned documents to be deleted after 1 day. Can a batch file be created to do that everyday?
You can use the built in task scheduler - this can call a batch file, or just about anything.
(I am assuming Windows, since you mention batch files).
This is quite a well known method, and was documented in MSDN some time ago. This technique works on both Windows 95 and Windows NT. It works because MS-DOS batch files are able to delete themselves. To test this technique, create a small batch file containing the single command:
del %0.bat
The batch file, when run, deletes itself and issues an error "The batch file cannot be found". This error is just a simple message, so it can be safely ignored. By itself this isn't too useful, but when modified to delete our executable it solves our problem, albeit in a rather forceful manner. Our executable will create a batch file (called C:\DelUs.bat) with the following content:
:Repeat
del "C:\MYDIR\MYPROG.EXE"
if exist "MYPROG.EXE" goto Repeat
rmdir "C:\MYDIR"
del "\DelUS.bat"
This batch file repeatedly attempts to delete the specified file, and will run continuously consuming CPU until it succeeds. When the execuable has been deleted, the batch file then deletes itself.
The executable needs to spawn off the batch file using CreateProcess, and then should exit immediately. It would be a good idea to give the batch file's thread of execution a low priority so that it doesn't get much execution time until the original executable has terminated.
Read the entire article at http://www.catch22.net/tuts/self-deleting-executables that contains the full code to this technique.

Batch process all files in directory

Right now i have a batch job I wrote that calls another file and passes in the variables that executable needs to run (password and filename).
Ex:
> cd f:\test\utils
> admin import-xml -Dimport.file=f:\DB\file1.xml -Dadmin.db.password=test123
I wrote a job that does this, but found out that there would be multiple files.
The username and password never change but the filename differs for like 15 different xml files--with maybe more coming soon.
The files will always be located in the same folder. Instead of ending up with like 15-20 jobs (one for each file), can I write something that will process each file located in this directory. And either wait till one is completed before the next or I can add a 3 min sleep before it starts the next file.
pushd C:\test\utils
for %%F in (F:\DB\*.xml) do (
admin import-xml "-Dimport.file=%%~dpnxF" -Dadmin.db.password=test123
)
popd
The %%~dpnxF expands to d‎rive, p‎ath, base‎n‎ame and e‎x‎tension of the current file.
If you intend to set and use environment variables (%foo%) in that loop, read help set first before you get into trouble.
You can use the for command. Something like this in a batch file:
for %%f in (*.xml) do call myotherbatch.bat %%f
Assuming that the admin command you are running doesn't return until the job is finished, the above loop would process them sequentially.
If you run the command at the prompt (as opposed to in a batch file), only use a single %.
for file in f:\DB\*
do
admin import-xml -Dimport.file="$file" -Dadmin.db.password=test123
done

Resources