Detect if file is open in batch file

Say I have a batch file to perform a long build, and in the end it creates an EXE. If I forget to close the application before the build starts, the communication phase will fail if it cannot re-create the EXE.

I want to check if the exe is open at the start of the build. I tried to rename the EXE file myself, but although this gives an access denied error, the rename command (which is an internal command) does not set% ErrorLevel%.

What is a non-destructive way to check an open file that sets% ErrorLevel% to a non-zero value?

+6
source share
3 answers

The renaming method did not work for me (tested on Windows XP SP3). I started an arbitrary application and tried to rename it to myself. There was no mistake, no effect.

However, this method did work:

COPY /B app.exe+NUL app.exe 

When the application started, this command caused an error message. And when the application was disconnected, not only this command saved the contents of the file, but also left the timestamp of the change unchanged.

If I were you, I would probably use this command (at the beginning of the script package, as you said) as follows:

 COPY /B app.exe+NUL app.exe >NUL || (GOTO :EOF) 

Operator || transfers control to the command / block next to it if the previous command did not work (raised the error level value). Therefore, the above command would end the script if COPY failed (what would happen if the file was opened).

The error message will be saved (since such messages are usually sent to the so-called standard error device and are not discarded with >NUL redirection, while other error messages are usually sent to standard output and, therefore, can be suppressed with >NUL ) and serve as an explanation for the premature completion of the script. However, if you want to display your own message, you can try something like this:

 COPY /B app.exe+NUL app.exe >NUL 2>NUL || (ECHO Target file inaccessible& GOTO :EOF) 

While >NUL hides everything that is sent to standard output, 2>NUL does the same for standard error.

+6
source
 @echo off :start ren filename filename // rename file to same name if errorlevel 1 goto errorline echo command successfull file is not in use anymore goto end :errorline echo Rename wasnt possible, file is in use try again in 5seconds timeout /T 5 goto :start :end exit 

renames the file to the same name, if possible, the script jumps to the end that exits the code, otherwize it gives an error code1 and goes to the error, after a timeout of 5 seconds it goes to: start and the script starts from the beginning.

+1
source

Found a better way:

 :start timeout /T 5 if exist %1 ( 2>nul ( >> %1 (call ) ) && (goto ende) || (goto start) ) else ( exit ) :ende YourCode 

This will be checked every 5 seconds if the file is being used, if it is restarted. if it does not fit, you can do the following options.

+1
source

Source: https://habr.com/ru/post/894458/


All Articles