Force batch file to load to RAM before running - windows

I have a batch file in an administrative partition of my portable drive, with a shortcut symlinked to it on the root of the drive. The purpose of the file is to unmount the drive and remount it as the specified letter (mostly for convenience).
When the file is opened, it is opened relative to the current letter rather than to the volume ID, so naturally, when the unmount happens, the command processor has no idea what to do next as it reads the file as needed rather than caching it.
There are two foreseeable solutions that I can think of but can't figure out:
Make the file get cached into RAM before executing
Make the file run relative to the volume ID instead of the mountpoint (tried using {VOLID}\file where {VOLID} is the volume ID, but it couldn't find the file although it was there (navigating to {VOLID}\ correctly opened the directory, but trying to open the file didn't correctly open the file.

Despite of the other answers, it's trivial to cache a whole batch script to RAM.
You only need to build a single block, as blocks are parsed and cached before they can be executed.
But blocks have some drawbacks, percent expansion doesn't work, therefore you need to use delayed expansion.
call and goto can't be used, as they would try to read from the file again.
(goto) 2>nul & (
echo The script is started
REM Need to change the directory, else the unmount doesn't work
c:
mountvol e: /p
mountvol g: \\?\Volume{VOLID}\
dir G:\
echo The script will end now
REM Here you need the goto 2>nul hack to avoid an error message
)
The (goto) 2>nul & seems strange here, but it's explained at SO:How to make a batch file delete itself?.
It works also without the goto, but then the scripts ends with an error message

Have the batch file determine where it is running from see this. If it's running from the portable drive have it make a copy of itself to a permanent drive location (c:\temp for instance) then run that copy of the batch file.
When running a bath file there is no concept of running it from RAM. Windows command processor will always go back to the .bat file for the 'next' command to run. If you edit a batch file while it's running the command processor will pick up your changes.

JJF wrote already the correct answer. It is not possible to copy a batch file to RAM and inform Windows command interpreter to interpret the command lines in memory. It would be possible to create a RAM disk, copy the batch file to the RAM disk and run it from there. But this just makes the task more complicated than necessary.
This commented batch code demonstrates how to copy a batch file to directory for temporary files and start it there for complete processing in a separate Windows command process.
#echo off
rem Is the batch file path not the path of directory for temporary files?
if /I not "%~dp0" == "%TEMP%\" (
rem Copy the batch file to directory for temporary files.
copy "%~f0" "%TEMP%" >nul
rem Run the copy in a separate command process with name of the batch
rem file with extension as window title and exit this batch process.
start "%~nx0" "%TEMP%\%~nx0"
goto :EOF
)
echo The batch file is now running from directory for temporary files.
echo.
pause
rem Delete the batch file in directory for temporary files
rem and exit the command process started for this batch file.
del "%TEMP%\%~nx0" & exit
Replace the two echo commands and the pause command by your batch code.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /? ... explains %~dp0 (drive and path of argument 0 which is the batch file itself) and %~nx0 (name and extension of batch file)
copy /?
del /?
echo /?
exit /?
goto /?
if /?
pause /?
rem /?
start /?
See also answer on Single line with multiple commands using Windows batch file for an explanation of operator & used here two run the two commands del and exit read from one line to avoid an opened console window with an error message as batch file deleted unexpected for the Windows command interpreter while processing it.

Related

I'm trying to use Robocopy to replace a cmd file

I've created a cmd file which uses the Robocopy command to update some files on the PC, but I can't replace the cmd files, because this contains the Robocopy script which is doing the updating. How do you replace a file which is doing the replacing?
I've moved the cmd file to another directory, which allows me to update most of the files, but I still can't replace the cmd file.
The Flags I'm using in Robocopy are /MIR /Copy:DAT /DCOPY:T
The Robocopy stopped at the cmd file and I can't replace it.
I don't see any reason for %SystemRoot%\System32\robocopy.exe failing to copy the batch file currently processed by cmd.exe than this batch file is additionally opened in an application like a text editor which prevents write access and deletion of the file as long as it is opened in the application.
However, the following code added to your batch file with unknown content could solve the problem.
#echo off
if /I not "%~dp0" == "%TEMP%\" (
copy /Y "%~f0" "%TEMP%" >nul 2>&1
if exist "%TEMP%\%~nx0" (
set "CurrentDirectory=%CD%"
set "InitialExecution=%~dp0"
cd /D "%TEMP%"
"%TEMP%\%~nx0" %*
)
)
rem Insert here other commands to execute by the batch
rem file now running from directory of temporary files.
rem The next three commands are only for demonstration.
if defined CurrentDirectory echo Initial current directory: %CurrentDirectory%
if defined InitialExecution echo Initial execution path: %InitialExecution%
pause
set "InitialExecution="
if defined CurrentDirectory set "CurrentDirectory=" & cd /D "%CurrentDirectory%" 2>nul & (goto) 2>nul & del "%~f0"
This batch file first checks if it is started from directory for temporary files. This is not the case on double clicking on the batch file, except the batch file is stored by chance in directory for temporary files by the user and double clicked on it in this directory. If batch file is not stored in directory for temporary files, it does following:
The batch file copies itself to directory of temporary files (only read access).
It verifies if the file copy was really successful which should be always true.
It defines two environment variables with path of current directory and initial execution path for later usage.
It sets the current directory to directory for temporary files.
This makes it possible to even delete the directory containing batch file on batch file directory being also current directory as typical on double clicking on a batch file stored on a local drive executed by current user.
The batch file runs itself from within directory for temporary files with passing all arguments passed to the batch file on initial execution further on its copy.
The Windows command processor cmd.exe executing the batch file continues batch file processing on its copy in temporary files directory with first line #echo off returning never to the initial batch file as started by the user.
Now with batch file processing done on a copy of initial batch file in temporary files directory and with current directory being also the directory for temporary files, the other commands in batch file can do everything in initial current directory respectively initial execution directory of the batch file like updating the files in these directories or even deleting these directories temporarily or permanently.
The three comment lines with command rem and the next three lines just demonstrate what can be done here and how to use the environment variables set by the batch file on initial execution. The two environment variables do not exist (most likely) on batch file being initially stored in directory for temporary files and executed by the user from this directory.
The batch file deletes the environment variable InitialExecution independent on its existence to restore initial environment in case of batch file executed from within a command prompt window.
Finally with batch file initially not executed from temporary files directory it deletes also the environment variable CurrentDirectory, changes the current directory back to initial current directory, if that directory still exists, and deletes itself from directory for temporary files.
(goto) 2>nul & del "%~f0" for batch file deletion without any error message output by Windows command processor was copied by me from Dave Benham's answer on How to make a batch file delete itself?
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /? ... explains %~dp0, %~f0 and %~nx0
cd /?
copy /?
del /?
echo /?
goto /?
if /?
pause /?
set /?
See also the Microsoft article about Using command redirection operators.

How to recursively delete all folders of a folder tree unless they contain a file with certain file extension?

How to go though a directory tree and delete all directories unless they contain a file with a particular file extension?
I tried Robocopy thinking the folders were empty. But all the folders have hidden files. So I need something that will take every folder in a directory that does not have a .pdf for example in it and delete it.
The task is to delete all directories/folders not containing a PDF file and also not containing a subdirectory/subfolder containing a PDF file. Let us look on an example to better understand the directory/folder deletion task.
The directory C:\Temp contains following subfolders and files:
Folder 1
Subfolder A
File 1A.txt
Subfolder B
File 1B.txt
Subfolder C
File 1C.pdf
File 1.cmd
Folder 2
Subfolder A
Subfolder B
File 2B.pdf
Subfolder C
File 2C.pdf
File 2.jpg
Folder 3
Subfolder A
File 3A.log
Subfolder B
File 3.doc
Last Folder & End
Subfolder A
Last File A.xls
Subfolder B
Subfolder C
Last File C.pdf
A folder is formatted bold. A hidden folder is formatted bold and italic. A hidden file is formatted italic.
The wanted folders and files after running the batch file should be:
Folder 1
Subfolder C
File 1C.pdf
File 1.cmd
Folder 2
Subfolder B
File 2B.pdf
Subfolder C
File 2C.pdf
File 2.jpg
Last Folder & End
Subfolder C
Last File C.pdf
This result can be achieved by executing following batch file:
#echo off
goto MainCode
:ProcessFolder
for /F "delims=" %%I in ('dir "%~1" /AD /B 2^>nul') do call :ProcessFolder "%~1\%%I"
if exist "%~1\*.pdf" goto :EOF
for /F "delims=" %%I in ('dir "%~1" /AD /B 2^>nul') do goto :EOF
if /I "%~1\" == "%BatchFilePath%" goto :EOF
rd /Q /S "%~1"
goto :EOF
:MainCode
setlocal EnableExtensions DisableDelayedExpansion
set "BatchFilePath=%~dp0"
if exist "C:\Temp\" cd /D "C:\Temp" & call :ProcessFolder "C:\Temp"
endlocal
Doing something recursively on a directory tree requires having a subroutine/function/procedure which calls itself recursively. In the batch file above this is ProcessFolder.
Please read the answer on Where does GOTO :EOF return to? The command goto :EOF is used here to exit the subroutine ProcessFolder and works only as wanted with enabled command extensions. FOR and CALL as used here require also enabled command extensions.
The main code of the batch file first enables explicitly the command extensions required for this batch file and disables delayed environment variable expansion to process correct also folders with an exclamation mark in name. This is the default environment on Windows, but it is better here to explicitly set this environment because the batch file contains the command RD with the options /Q /S which can be really very harmful on execution from within wrong environment or directory.
The subroutine ProcessFolder is not at end of the batch file as usual with a goto :EOF above to avoid an unwanted fall through to the command lines of the subroutine after finishing the entire task. For safety reasons the subroutine is in the middle of the batch file. So if a user tries to execute the batch file on Windows 95/98 with no support for command extensions nothing bad happens because first goto MainCode is executed successfully as expected, but SETLOCAL command line, calling the subroutine and last also ENDLOCAL fail and so no directory was deleted by this batch file designed for Windows with cmd.exe as Windows command processor instead of command.com.
The main code sets also current directory to the directory to process. So C:\Temp itself is never deleted by this code because of Windows prevents the deletion of a directory which is the current directory of any running process or contains a file opened by a running process with file access permission set to prevent other processes to delete the file while being opened by the process.
Next is called subroutine ProcessFolder with argument C:\Temp to process this folder recursively.
Last the initial environment is restored which includes also initial current directory on starting the batch file if this directory still exists.
The command for /D is usually used to do something on all subdirectories of a directory. But this is not possible here because FOR always ignores directories and files with hidden attribute set. For that reason it is necessary to use command DIR to get a list of all subdirectories in current directory including directories with hidden attribute set.
The command line dir "%~1" /AD /B 2>nul is executed by FOR in a separate command process started with cmd.exe /C in background. This is one reason why this batch file is quite slow. The other reason is calling the subroutine again and again which cause internally in cmd.exe to save and restore environment again and again.
Please read the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded dir command line with using a separate command process started in background.
For each subdirectory in a directory the subroutine ProcessFolder calls itself. The first FOR loop in the subroutine is left if a directory does not contain one more subdirectory.
Then the subroutine checks in current directory if there is at least one *.pdf file. The IF condition used here is true even if the directory contains only a hidden PDF file. In this case the subroutine is exited without doing anything as this directory contains definitely a PDF file and therefore must be kept according to the requirements of the folder deletion task.
Next is checked if the current directory still contains at least one subdirectory as in this case the current directory must be also kept as one of its subdirectories contains at least one PDF file.
Last the subroutine checks if the current directory contains by chance the batch file as this directory must be also kept to finish the processing of the batch file.
Otherwise the current directory is deleted with all files on not containing a PDF file and no subdirectories and also not the currently running batch file as long as Windows does not prevent the deletion of the directory because of missing permissions or a sharing access violation.
Please note that the batch file does not delete other files in a directory which is not deleted as it can be seen also on the example.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /?
cd /?
dir /?
echo /?
endlocal /?
for /?
goto /?
if /?
rd /?
setlocal /?

How to maintain a file association when calling a program from a batch file?

Is there a way to maintain the original file association when running a program from a batch file?
I created a batch file that calls a Windows program and performs some file maintenance. I changed the file association to the batch file. When I click on a file that's associated with that program, the batch file executes and opens the program but the file I click on isn't loaded. The original file association is lost.
This sorta makes sense because the CALL command within the batch file is once removed from the initial mouse-click that initiated the batch file.
Is there a syntax I can add that would pass the target file name to the batch file as a variable and append it to the CALL command line?
BTW, this is for an XP machine. Any assistance would be appreciated!
EDIT: here's the code I'm trying to write:
call "C:\Program Files\CorelDRAW X4\Programs\CorelDRW.exe"
:loop
if exist "C:\Documents and Settings\<user>\My Documents\corel user files\*.cdr" copy "C:\Documents and Settings\<user>\My Documents\corel user files\*.cdr" "C:\Documents and Settings\<user>\My Documents\corel user files\*.sav"
ping localhost -n 300 > nul
goto loop
I'm trying to protect CorelDraw's auto-save file. There's a bug whereby CorelDraw sometimes deletes the auto-save file during abnormal shut-down. I changed the .cdr file association so that clicking on a cdr file calls the batch file, which in turn calls Coreldraw and copies the auto-save file to a different filename. That part works, but I have to manually open the file I clicked on.
Ideally, I'd like to figure out a way to terminate the loop when I close CorelDraw, but I'll cross that bridge once I solve the file association problem.
EDIT2: Here is the result of echo %CMDCMDLINE%:
C:\WINDOWS\system32\cmd.exe /c ""C:\Documents and Settings\<user>\My Documents\corel user files\protect_autosave.bat" "C:\Documents and Settings\<user>\My Documents\filename.cdr""
As far as I have understood the requirements for the task the code to use in batch file %ProgramFiles%\CorelDRAW X4\Programs\CorelFile.bat is:
#echo off
if "%~1" == "" goto :EOF
"%ProgramFiles%\CorelDRAW X4\Programs\CorelDRW.exe" %*
for %%I in (%*) do if exist %%I copy /Y "%%~I" "%%~dpnI.sav" >nul
This batch file must be associated with file extension .cdr for example by importing following registry file on Windows XP and later Windows versions with administrator privileges:
REGEDIT4
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.cdr]
#="CorelDrawFile"
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CorelDrawFile]
#="Corel Draw Image"
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CorelDrawFile\DefaultIcon]
#=hex(2):22,25,50,72,6f,67,72,61,6d,46,69,6c,65,73,25,5c,43,6f,72,65,6c,44,52,\
41,57,20,58,34,5c,50,72,6f,67,72,61,6d,73,5c,43,6f,72,65,6c,44,52,57,2e,65,\
78,65,22,2c,30,00
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CorelDrawFile\shell\open\command]
#=hex(2):22,25,50,72,6f,67,72,61,6d,46,69,6c,65,73,25,5c,43,6f,72,65,6c,44,52,\
41,57,20,58,34,5c,50,72,6f,67,72,61,6d,73,5c,43,6f,72,65,6c,46,69,6c,65,2e,\
62,61,74,22,20,22,25,31,22,00
It is also possible to register file extension .cdr with absolute paths with REG_SZ instead of using REG_EXPAND_SZ and %ProgramFiles% in paths.
REGEDIT4
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.cdr]
#="CorelDrawFile"
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CorelDrawFile]
#="Corel Draw Image"
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CorelDrawFile\DefaultIcon]
#="\"C:\\Program Files\\CorelDRAW X4\\Programs\\CorelDRW.exe\",0"
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CorelDrawFile\shell\open\command]
#="\"C:\\Program Files\\CorelDRAW X4\\Programs\\CorelFile.bat\" \"%1\""
Windows Explorer calls for each selected *.cdr file the batch file on using context menu Open respectively on double clicking a single *.cdr file.
The batch file starts Corel Draw with all the arguments passed to the batch file passing to Corel Draw. This is usually just the file name of the *.cdr file with full path and file extension enclosed in double quotes.
After Corel Draw terminated, the batch file checks for existence of each file specified as command line argument and copies the file with same name in same directory with different file extension .sav.
The batch file is designed for being started with multiple *.cdr file names specified as arguments on command line. I don't know if Corel Draw supports multiple *.cdr files being specified on command line.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /? ... explains %* (batch file) and %1 (Windows registry).
copy /?
echo /?
for /?
if /?

Command to run a .bat file

I'm trying to make my Visual Studio build script execute a .bat file that does something important.
Here is what I'm want to do right now:
cd "F:\- Big Packets -\kitterengine\Common\" Template.bat
But it doesn't work.
I have to do this to make it work:
cd "F:\- Big Packets -\kitterengine\Common\"
F:
Template.bat
But this is pretty difficult to add to the Visual Studio script.
How can I do this in one single line?
"F:\- Big Packets -\kitterengine\Common\Template.bat" maybe prefaced with call (see call /?). Or Cd /d "F:\- Big Packets -\kitterengine\Common\" & Template.bat.
CMD Cheat Sheet
Cmd.exe
Getting Help
Punctuation
Naming Files
Starting Programs
Keys
CMD.exe
First thing to remember its a way of operating a computer. It's the way we did it before WIMP (Windows, Icons, Mouse, Popup menus) became common. It owes it roots to CPM, VMS, and Unix. It was used to start programs and copy and delete files. Also you could change the time and date.
For help on starting CMD type cmd /?. You must start it with either the /k or /c switch unless you just want to type in it.
Getting Help
For general help. Type Help in the command prompt. For each command listed type help <command> (eg help dir) or <command> /? (eg dir /?).
Some commands have sub commands. For example schtasks /create /?.
The NET command's help is unusual. Typing net use /? is brief help. Type net help use for full help. The same applies at the root - net /? is also brief help, use net help.
References in Help to new behaviour are describing changes from CMD in OS/2 and Windows NT4 to the current CMD which is in Windows 2000 and later.
WMIC is a multipurpose command. Type wmic /?.
Punctuation
& seperates commands on a line.
&& executes this command only if previous command's errorlevel is 0.
|| (not used above) executes this command only if previous command's
errorlevel is NOT 0
> output to a file
>> append output to a file
< input from a file
2> Redirects command error output to the file specified. (0 is StdInput, 1 is StdOutput, and 2 is StdError)
2>&1 Redirects command error output to the same location as command output.
| output of one command into the input of another command
^ escapes any of the above, including itself, if needed to be passed
to a program
" parameters with spaces must be enclosed in quotes
+ used with copy to concatenate files. E.G. copy file1+file2 newfile
, used with copy to indicate missing parameters. This updates the files
modified date. E.G. copy /b file1,,
%variablename% a inbuilt or user set environmental variable
!variablename! a user set environmental variable expanded at execution
time, turned with SelLocal EnableDelayedExpansion command
%<number> (%1) the nth command line parameter passed to a batch file. %0
is the batchfile's name.
%* (%*) the entire command line.
%CMDCMDLINE% - expands to the original command line that invoked the
Command Processor (from set /?).
%<a letter> or %%<a letter> (%A or %%A) the variable in a for loop.
Single % sign at command prompt and double % sign in a batch file.
\\ (\\servername\sharename\folder\file.ext) access files and folders via UNC naming.
: (win.ini:streamname) accesses an alternative steam. Also separates drive from rest of path.
. (win.ini) the LAST dot in a file path separates the name from extension
. (dir .\*.txt) the current directory
.. (cd ..) the parent directory
\\?\ (\\?\c:\windows\win.ini) When a file path is prefixed with \\?\ filename checks are turned off.
Naming Files
< > : " / \ | Reserved characters. May not be used in filenames.
Reserved names. These refer to devices eg,
copy filename con
which copies a file to the console window.
CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4,
COM5, COM6, COM7, COM8, COM9, LPT1, LPT2,
LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9
CONIN$, CONOUT$, CONERR$
--------------------------------
Maximum path length 260 characters
Maximum path length (\\?\) 32,767 characters (approx - some rare characters use 2 characters of storage)
Maximum filename length 255 characters
Starting a Program
See start /? and call /? for help on all three ways.
There are two types of Windows programs - console or non console (these are called GUI even if they don't have one). Console programs attach to the current console or Windows creates a new console. GUI programs have to explicitly create their own windows.
If a full path isn't given then Windows looks in
The directory from which the application loaded.
The current directory for the parent process.
Windows NT/2000/XP: The 32-bit Windows system directory. Use the
GetSystemDirectory function to get the path of this directory. The
name of this directory is System32.
Windows NT/2000/XP: The 16-bit Windows system directory. There is no
function that obtains the path of this directory, but it is
searched. The name of this directory is System.
The Windows directory. Use the GetWindowsDirectory function to get
the path of this directory.
The directories that are listed in the PATH environment variable.
Specify a program name
This is the standard way to start a program.
c:\windows\notepad.exe
In a batch file the batch will wait for the program to exit. When
typed the command prompt does not wait for graphical
programs to exit.
If the program is a batch file control is transferred and the rest of the calling batch file is not executed.
Use Start command
Start starts programs in non standard ways.
start "" c:\windows\notepad.exe
Start starts a program and does not wait. Console programs start in a new window. Using the /b switch forces console programs into the same window, which negates the main purpose of Start.
Start uses the Windows graphical shell - same as typing in WinKey + R (Run dialog). Try
start shell:cache
Also program names registered under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths can also be typed without specifying a full path.
Also note the first set of quotes, if any, MUST be the window title.
Use Call command
Call is used to start batch files and wait for them to exit and continue the current batch file.
Other Filenames
Typing a non program filename is the same as double clicking the file.
Keys
Ctrl + C exits a program without exiting the console window.
For other editing keys type Doskey /?.
↑ and ↓ recall commands
ESC clears command line
F7 displays command history
ALT+F7 clears command history
F8 searches command history
F9 selects a command by number
ALT+F10 clears macro definitions
Also not listed
Ctrl + ←orβ†’ Moves a word at a time
Ctrl + Backspace Deletes the previous word
Home Beginning of line
End End of line
Ctrl + End Deletes to end of line
Can refer to here: https://ss64.com/nt/start.html
start "" /D F:\- Big Packets -\kitterengine\Common\ /W Template.bat
There are many possibilities to solve this task.
1. RUN the batch file with full path
The easiest solution is running the batch file with full path.
"F:\- Big Packets -\kitterengine\Common\Template.bat"
Once end of batch file Template.bat is reached, there is no return to previous script in case of the command line above is within a *.bat or *.cmd file.
The current directory for the batch file Template.bat is the current directory of the current process. In case of Template.bat requires that the directory of this batch file is the current directory, the batch file Template.bat should contain after #echo off as second line the following command line:
cd /D "%~dp0"
Run in a command prompt window cd /? for getting displayed the help of this command explaining parameter /D ... change to specified directory also on a different drive.
Run in a command prompt window call /? for getting displayed the help of this command used also in 2., 4. and 5. solution and explaining also %~dp0 ... drive and path of argument 0 which is the name of the batch file.
2. CALL the batch file with full path
Another solution is calling the batch file with full path.
call "F:\- Big Packets -\kitterengine\Common\Template.bat"
The difference to first solution is that after end of batch file Template.bat is reached the batch processing continues in batch script containing this command line.
For the current directory read above.
3. Change directory and RUN batch file with one command line
There are 3 operators for running multiple commands on one command line: &, && and ||.
For details see answer on Single line with multiple commands using Windows batch file
I suggest for this task the && operator.
cd /D "F:\- Big Packets -\kitterengine\Common" && Template.bat
As on first solution there is no return to current script if this is a *.bat or *.cmd file and changing the directory and continuation of batch processing on Template.bat is successful.
4. Change directory and CALL batch file with one command line
This command line changes the directory and on success calls the batch file.
cd /D "F:\- Big Packets -\kitterengine\Common" && call Template.bat
The difference to third solution is the return to current batch script on exiting processing of Template.bat.
5. Change directory and CALL batch file with keeping current environment with one command line
The four solutions above change the current directory and it is unknown what Template.bat does regarding
current directory
environment variables
command extensions state
delayed expansion state
In case of it is important to keep the environment of current *.bat or *.cmd script unmodified by whatever Template.bat changes on environment for itself, it is advisable to use setlocal and endlocal.
Run in a command prompt window setlocal /? and endlocal /? for getting displayed the help of these two commands. And read answer on change directory command cd ..not working in batch file after npm install explaining more detailed what these two commands do.
setlocal & cd /D "F:\- Big Packets -\kitterengine\Common" & call Template.bat & endlocal
Now there is only & instead of && used as it is important here that after setlocal is executed the command endlocal is finally also executed.
ONE MORE NOTE
If batch file Template.bat contains the command exit without parameter /B and this command is really executed, the command process is always exited independent on calling hierarchy. So make sure Template.bat contains exit /B or goto :EOF instead of just exit if there is exit used at all in this batch file.
You can use Cmd command to run Batch file.
Here is my way =>
cmd /c ""Full_Path_Of_Batch_Here.cmd" "
More information => cmd /?
Like Linux, to run the myapp.exe, you can use only one of these three methods.
use system path
add project directory to your systeme path, then:
myapp.exe
or
myapp
use full long path
\path\to\project\myapp.exe
go to working directory
cd \path\to\project
.\myapp.exe

Can I prevent a batch file to be executed by more than 1 user at the same time

I have a batch file which can update a web project and clean/rebuild it. I made it executable for network users. Now I want to make the batch executable only by one user at the same time. Like synchronize object in programming languages.
Is there a possibility to do that?
A simple solution to check if batch file is already running is using file system.
The batch file can check if a file exists and denies execution in this case, otherwise it creates the file, runs the commands and finally deletes the file.
#echo off
if exist "C:\Temp\BatchLock.txt" goto BatchRunning
echo Batch file is running by %username%.>C:\Temp\BatchLock.txt
rem All other commands of the batch file
del C:\Temp\BatchLock.txt
goto :EOF
:BatchRunning
type C:\Temp\BatchLock.txt
echo/
echo Please run the batch later again.
echo/
echo Press any key to exit ...
pause >nul
Of course C:\Temp is not a good storage location for the lock text file. It must be a directory which is identical for all users, a directory on server with write permissions for all users.

Resources