Why is here difference in this 2 cases of command execution? - windows

I need to run two commands in paralel with double quotation (the simple one won't work in my case) and wait for the results. But when I do this, I get a different behavior with double qouted execution (my command simply won't run for unknown reason).
I've simplified the problem to this example:
(
start "task1" cmd /C "timeout /t 5 /nobreak > nul"
start "task2" cmd /C ""timeout /t 8 /nobreak > nul""
) | pause
You can see that in the later case the counter will count down, but not in the first case
Waiting for 8 seconds, press CTRL+C to quit ...
Question:
What causes the change between those two cases?
How can this changed behavior avoided?
In my special case:
When I run this everything works fine:
start "task1" cmd /C ""D:\Program Files\Alteryx\bin\AlteryxEngineCmd.exe" "^<WizardValues^> ^<Module^>D:\long path\aaa.yxwz^</Module^> ^<Value name='Drop Down (31)'^>2019-08^</Value^> ^</WizardValues^>" > outp1.txt "
When I put the simple version into a complex one the execution simply fails:
(
start "task1" cmd /C ""D:\Program Files\Alteryx\bin\AlteryxEngineCmd.exe" "^<WizardValues^> ^<Module^>D:\long path\aaa.yxwz^</Module^> ^<Value name='Drop Down (12)'^>2019-08^</Value^> ^</WizardValues^>" > outp1.txt "
start "task2" cmd /C ""D:\Program Files\Alteryx\bin\AlteryxEngineCmd.exe" "^<WizardValues^> ^<Module^>D:\long path\bbb.yxwz^</Module^> ^<Value name='Drop Down (34)'^>2019-07^</Value^> ^</WizardValues^>" > outp2.txt "
) | pause
Question:
How this change in behavior is similar to the above example?

Concerning your test scenario:
In cmd /C "timeout /t 5 /nobreak > nul" the redirection operator > is hidden from the hosting cmd instance (the one that runs the code of your batch file), so it becomes executed in the inner cmd instance.
In cmd /C ""timeout /t 5 /nobreak > nul"" the > is exposed to the hosting cmd instance, so redirection is executed there and the inner one does not receive the > nul part.
(Though what surprises me a bit is that no syntax error arises due to the double-quotation; I could imagine that the second start command actually receives something like ""timeout /t 5 /nobreak to execute, where it seems to remove the leading "" from, but I am not quite sure.)
Concerning your special case:
Forget about escaping within your XML-like string, just escape the outer quotes and the redirection operator.
Running the program alone:
start "task1" cmd /C ^""D:\Program Files\Alteryx\bin\AlteryxEngineCmd.exe" "<WizardValues> <Module>D:\long path\aaa.yxwz</Module> <Value name='Drop Down (31)'>2019-08</Value> </WizardValues>" ^> "outp1.txt"^"
Running the program in the pipe (|) requires double-escaping, since either side is executed by cmd /S /D /c on its own here:
(
start "task1" cmd /C ^^^""D:\Program Files\Alteryx\bin\AlteryxEngineCmd.exe" "<WizardValues> <Module>D:\long path\aaa.yxwz</Module> <Value name='Drop Down (12)'>2019-08</Value> </WizardValues>" ^^^> "outp1.txt"^^^"
start "task2" cmd /C ^^^""D:\Program Files\Alteryx\bin\AlteryxEngineCmd.exe" "<WizardValues> <Module>D:\long path\bbb.yxwz</Module> <Value name='Drop Down (34)'>2019-07</Value> </WizardValues>" ^^^> "outp2.txt"^^^"
) | pause ^> nul
Unfortunately you cannot just omit the (escaped) outer pair of quotation marks, because cmd is not quite intelligent when handling them. Something like cmd /C "program.exe" "quoted string" leaves the command line program.exe" "quoted string behind, which is of course invalid syntax.
N. B.:
Usually an external program can be started using without cmd /C, but in your situation you are using output redirection >, which is a thing internal to cmd, that is why you need it.

Related

Running Flutter/Dart commands in batch script halts execution [duplicate]

I'm trying to get my commit-build.bat to execute other .BAT files as part of our build process.
Content of commit-build.bat:
"msbuild.bat"
"unit-tests.bat"
"deploy.bat"
This seems simple enough, but commit-build.bat only executes the first item in the list (msbuild.bat).
I have run each of the files separately with no problems.
Use:
call msbuild.bat
call unit-tests.bat
call deploy.bat
When not using CALL, the current batch file stops and the called batch file starts executing. It's a peculiar behavior dating back to the early MS-DOS days.
All the other answers are correct: use call. For example:
call "msbuild.bat"
History
In ancient DOS versions it was not possible to recursively execute batch files. Then the call command was introduced that called another cmd shell to execute the batch file and returned execution back to the calling cmd shell when finished.
Obviously in later versions no other cmd shell was necessary anymore.
In the early days many batch files depended on the fact that calling a batch file would not return to the calling batch file. Changing that behaviour without additional syntax would have broken many systems like batch menu systems (using batch files for menu structures).
As in many cases with Microsoft, backward compatibility therefore is the reason for this behaviour.
Tips
If your batch files have spaces in their names, use quotes around the name:
call "unit tests.bat"
By the way: if you do not have all the names of the batch files, you could also use for to do this (it does not guarantee the correct order of batch file calls; it follows the order of the file system):
FOR %x IN (*.bat) DO call "%x"
You can also react on errorlevels after a call. Use:
exit /B 1 # Or any other integer value in 0..255
to give back an errorlevel. 0 denotes correct execution. In the calling batch file you can react using
if errorlevel neq 0 <batch command>
Use if errorlevel 1 if you have an older Windows than NT4/2000/XP to catch all errorlevels 1 and greater.
To control the flow of a batch file, there is goto :-(
if errorlevel 2 goto label2
if errorlevel 1 goto label1
...
:label1
...
:label2
...
As others pointed out: have a look at build systems to replace batch files.
If we want to open multiple command prompts then we could use
start cmd /k
/k: is compulsory which will execute.
Launching many command prompts can be done as below.
start cmd /k Call rc_hub.bat 4444
start cmd /k Call rc_grid1.bat 5555
start cmd /k Call rc_grid1.bat 6666
start cmd /k Call rc_grid1.bat 5570.
Try:
call msbuild.bat
call unit-tests.bat
call deploy.bat
You are calling multiple batches in an effort to compile a program.
I take for granted that if an error occurs:
1) The program within the batch will exit with an errorlevel;
2) You want to know about it.
for %%b in ("msbuild.bat" "unit-tests.bat" "deploy.bat") do call %%b|| exit /b 1
'||' tests for an errorlevel higher than 0. This way all batches are called in order but will stop at any error, leaving the screen as it is for you to see any error message.
If we have two batch scripts, aaa.bat and bbb.bat, and call like below
call aaa.bat
call bbb.bat
When executing the script, it will call aaa.bat first, wait for the thread of aaa.bat terminate, and call bbb.bat.
But if you don't want to wait for aaa.bat to terminate to call bbb.bat, try to use the START command:
START ["title"] [/D path] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED]
[/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL]
[/AFFINITY <hex affinity>] [/WAIT] [/B] [command/program]
[parameters]
Exam:
start /b aaa.bat
start /b bbb.bat
call msbuild.bat
call unit-tests.bat
call deploy.bat
using "&"
As you have noticed executing the bat directly without CALL,START, CMD /C causes to enter and execute the first file and then the process to stop as the first file is finished. Though you still can use & which will be the same as using command1 & command2 directly in the console:
(
first.bat
)&(
second.bat
)& (
third.bat
)&(
echo other commands
)
In a term of machine resources this will be the most efficient way though in the last block you won't be able to use command line GOTO,SHIFT,SETLOCAL.. and its capabilities will almost the same as in executing commands in the command prompt. And you won't be able to execute other command after the last closing bracket
Using CALL
call first.bat
call second.bat
call third.bat
In most of the cases it will be best approach - it does not create a separate process but has almost identical behaviour as calling a :label as subroutine. In MS terminology it creates a new "batch file context and pass control to the statement after the specified label. The first time the end of the batch file is encountered (that is, after jumping to the label), control returns to the statement after the call statement."
You can use variables set in the called files (if they are not set in a SETLOCAL block), you can access directly labels in the called file.
CMD /C, Pipes ,FOR /F
Other native option is to use CMD /C (the /C switch will force the called console to exit and return the control)
Something that cmd.exe is doing in non transparent way with using FOR /F against bat file or when pipes are used.
This will spawn a child process that will have all the environment ot the calling bat.
Less efficient in terms of resources but as the process is separate ,parsing crashes or calling an EXIT command will not stop the calling .bat
#echo off
CMD /c first.bat
CMD /C second.bat
::not so different than the above lines.
:: MORE,FINDSTR,FIND command will be able to read the piped data
:: passed from the left side
break|third.bat
START
Allows you more flexibility as the capability to start the scripts in separate window , to not wait them to finish, setting a title and so on. By default it starts the .bat and .cmd scripts with CMD /K which means that the spawned scripts will not close automatically.Again passes all the environment to the started scripts and consumes more resources than cmd /c:
:: will be executed in the same console window and will wait to finish
start "" /b /w cmd /c first.bat
::will start in a separate console window and WONT wait to be finished
:: the second console window wont close automatically so second.bat might need explicit exit command
start "" second.bat
::Will start it in a separate window ,but will wait to finish
:: closing the second window will cause Y/N prompt
:: in the original window
start "" /w third.cmd
::will start it in the same console window
:: but wont wait to finish. May lead to a little bit confusing output
start "" /b cmd /c fourth.bat
WMIC
Unlike the other methods from now on the examples will use external of the CMD.exe utilities (still available on Windows by default).
WMIC utility will create completely separate process so you wont be able directly to wait to finish. Though the best feature of WMIC is that it returns the id of the spawned process:
:: will create a separate process with cmd.exe /c
WMIC process call create "%cd%\first.bat","%cd%"
::you can get the PID and monitoring it with other tools
for /f "tokens=2 delims=;= " %%# in ('WMIC process call create "%cd%\second.bat"^,"%cd%" ^|find "ProcessId"') do (
set "PID=%%#"
)
echo %PID%
You can also use it to start a process on a remote machine , with different user and so on.
SCHTASKS
Using SCHTASKS provides some features as (obvious) scheduling , running as another user (even the system user) , remote machine start and so on. Again starts it in completely separate environment (i.e. its own variables) and even a hidden process, xml file with command parameters and so on :
SCHTASKS /create /tn BatRunner /tr "%cd%\first.bat" /sc ONCE /sd 01/01/1910 /st 00:00
SCHTASKS /Run /TN BatRunner
SCHTASKS /Delete /TN BatRunner /F
Here the PID also can acquired from the event log.
ScriptRunner
Offers some timeout between started scripts. Basic transaction capabilities (i.e. rollback on error) and the parameters can be put in a separate XML file.
::if the script is not finished after 15 seconds (i.e. ends with pause) it will be killed
ScriptRunner.exe -appvscript %cd%\first.bat -appvscriptrunnerparameters -wait -timeout=15
::will wait or the first called script before to start the second
:: if any of the scripts exit with errorcode different than 0 will try
:: try to restore the system in the original state
ScriptRunner.exe -appvscript second.cmd arg1 arg2 -appvscriptrunnerparameters -wait -rollbackonerror -appvscript third.bat -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror
To call a .bat file within a .bat file, use
call foo.bat
(Yes, this is silly, it would make more sense if you could call it with foo.bat, like you could from the command prompt, but the correct way is to use call.)
Simplest Way To Run Multiple Batch Files Parallelly
start "systemLogCollector" /min cmd /k call systemLogCollector.bat
start "uiLogCollector" /min cmd /k call uiLogCollector.bat
start "appLogCollector" /min cmd /k call appLogCollector.bat
Here three batch files are run on separate command windows in a minimized state. If you don't want them minimized, then remove /min. Also, if you don't need to control them later, then you can get rid of the titles. So, a bare-bone command will be- start cmd /k call systemLogCollector.bat
If you want to terminate them, then run these commands-
taskkill /FI "WindowTitle eq appLogCollector*" /T /F
taskkill /FI "WindowTitle eq uiLogCollector*" /T /F
taskkill /FI "WindowTitle eq systemLogCollector*" /T /F
Start msbuild.bat
Start unit-tests.bat
Start deploy.bat
If that doesn't work, replace start with call or try this:
Start msbuild.bat
Goto :1
:1
Start unit-tests.bat
Goto :2
:2
Start deploy.bat
Looking at your filenames, have you considered using a build tool like NAnt or Ant (the Java version). You'll get a lot more control than with bat files.
If you want to open many batch files at once you can use the call command. However, the call command closes the current bat file and goes to another. If you want to open many at once, you may want to try this:
#echo off
start cmd "call ex1.bat&ex2.bat&ex3.bat"
And so on or repeat start cmd "call..." for however many files. This works for Windows 7, but I am not sure about other systems.
Your script should be:
start "msbuild.bat"
start "unit-tests.bat"
start "deploy.bat"
Just use the call command! Here is an example:
call msbuild.bat
call unit-tests.bat
call deploy.bat
With correct quoting (this can be tricky sometimes):
start "" /D "C:\Program Files\ProgramToLaunch" "cmd.exe" "/c call ""C:\Program Files\ProgramToLaunch\programname.bat"""
1st arg - Title (empty in this case)
2nd arg - /D specifies starting directory, can be ommited if want the current working dir (such as "%~dp0")
3rd arg - command to launch, "cmd.exe"
4th arg - arguments to command, with doubled up quotes for the arguments inside it (this is how you escape quotes within quotes in batch)
Running multiple scripts in one I had the same issue. I kept having it die on the first one not realizing that it was exiting on the first script.
:: OneScriptToRunThemAll.bat
CALL ScriptA.bat
CALL ScriptB.bat
EXIT
:: ScriptA.bat
Do Foo
EXIT
::ScriptB.bat
Do bar
EXIT
I removed all 11 of my scripts EXIT lines and tried again and all 11 ran in order one at a time in the same command window.
:: OneScriptToRunThemAll.bat
CALL ScriptA.bat
CALL ScriptB.bat
EXIT
::ScriptA.bat
Do Foo
::ScriptB.bat
Do bar
I know I am a bit late to the party, but here is another way. That is, this method should wait until the first one is done, the second, and so on.
start "" /wait cmd.exe /c msbuild.bat
start "" /wait cmd.exe /c unit-tests.bat
start "" /wait cmd.exe /c deploy.bat
The only issue that may come out of using this method, is that with new instances of cmd.exe being spawned, is that Errorlevel checking is kept within in each instance of cmd.exe.
Or..
start "" /wait call msbuild.bat
start "" /wait call unit-tests.bat
start "" /wait call deploy.bat
Hope this helps.

How to run batch files in background while running multiple files in parallel

I am writing a batch file which will execute 4 other batch files in parallel:
#echo off
echo %time%
(
start call s1.bat
start call s2.bat
start call s3.bat
start call s4.bat
) | set /P "="
echo %time%
But this is opening 4 new windows.
Can anyone help, how to avoid opening multiple windows and run all those 4 batch files in background?
Adding /B is on of the option, but I don't to where to add it exactly.
(
start /B call s1.bat
start /B call s2.bat
start /B call s3.bat
start /B call s4.bat
) | set /P "="
Is giving me an error:
The process tried to write to a nonexistent pipe.
As I do not want to use VB or any other script, how to do it in batch?
This is a really interesting problem! It seems that there is some conflict with the redirection handles.
The main script awaits execution of the sub-scripts with the following code (on Windows 10):
(
> nul start "" /B cmd /D /C call s1.bat
> nul start "" /B cmd /D /C call s2.bat
> nul start "" /B cmd /D /C call s3.bat
> nul start "" /B cmd /D /C call s4.bat
) | set /P =""
The > nul redirection prevents any data to be written to the pipe |. It seems as soon as there becomes anything written to the standard output handle STDOUT (1), the main script does no longer wait (and sometimes the error message The process tried to write to a nonexistent pipe. arises, possibly depending on how fast the sub-script(s) execute(s)). However, as soon as the /B is removed, output to STDOUT by the sub-scripts does not affect the behaviour of the main script, which waits for all sub-scripts, and > nul is therefore no longer necessary.
The explicit cmd /C part is necessary because start would otherwise implicitly use cmd /K when starting internal commands like call which leave non-terminated processes cmd.exe behind upon completion of the respective sub-script.
The /D switch just prevents any auto-run commands to become executed.
When you use normal start without /B for running the sub-scripts, a new instance of the command interpreter is started, that is the process cmd.exe, and a new instance of the console window is started as a process conhost.exe.
Now using start /B still creates a new process cmd.exe but it uses the current process conhost.exe.
I do not know what exactly happens in the background and how all these processes interact, but it appears to me that the issue is connected to the lack of conhost.exe processes when using start /B. Maybe conhost.exe is establishing the redirection handles and hence the pipe. Anyway, as long as there is nothing written to the pipe, there is nothing to conflict, so set /P ="" waits for the related handle to become closed.

what should be the program or script for task scheduler

Through cmd, this command works fine and my service ABC gets terminate and starts,
taskkill /f /fi "memusage gt 100" /im ABC.exe && NET START ABC
Now I want to create a task scheduler to run this script every day,
In Add Arguments, I put the command.
if I am putting CMD in program\script, then it's not working, what shall I put there?
or do we have other way to get it done?
You should add /C to the cmd.exe arguments followed by the command you want to execute.
This should work:
Program/script:
cmd.exe
Arguments:
/S /C "taskkill /f /fi "memusage gt 100" /im ABC.exe && NET START PeerDistSvc"
Where flags from cmd /?:
/C Carries out the command specified by string and then
terminates
/S Modifies the treatment of string after /C or /K
...
If /C or /K is specified, then the remainder of the command line after
the switch is processed as a command line, where the following logic
is used to process quote (") characters:
If ...:
no /S switch
...
Otherwise, old behavior is to see if the first character is
a quote character and if so, strip the leading character and
remove the last quote character on the command line, preserving
any text after the last quote character.
alternatively put your command into a script file say "mycommand.cmd"
MyCommand.cmd:
taskkill /f /fi "memusage gt 100" /im ABC.exe && NET START ABC
then just reference this CMD /BAT file in the action of the task scheduler.
This is the easiest option when you have anything complex or will want to modify the code in any way on a regular basis because modifying the code in the scheduled task itself will always require entering your credentials to edit it.
In addition if you have a separate script file you can manually run it by hand as needed without opening the scheduler and running the task on demand.

How to close CMD when another program is exited?

I want to close a cmd window when the program csgo.exe is exited. There is one cmd window open, which is ( node server.js ) and I would like the program to be stopped when csgo.exe is quit.
Here is the full .bat.
#ECHO OFF
start steam://rungameid/730
start cmd /K "cd C:\CSGO-HUD-master & node server.js"
start cmd /K "cd C:\Program Files (x86)\Mozilla Firefox & start firefox.exe http://localhost:2626/ & exit"
Thanks!
The is doable if you know the task name of the program you want to watch. Here is the code:
#echo off
:LOOP
tasklist|findstr calc.exe > nul
if %errorlevel%==1 goto ENDLOOP
ping 127.0.0.1 -n 2 > nul
goto LOOP
:ENDLOOP
exit
In this example we want our bat to terminate after the calculator (calc.exe) is closed.
To achieve this, we first execute tasklist which gives us a list of all running programs. Then we check the output for the occurrence of calc.exe. If it is still running, findstr calc.exe will set %errorlevel% to 0 so we can just jump back and check again. If calc.exe is not running, %errorlevel% will be set to 1 so we know that we can jump out of the loop and terminate.
I've added the line ping 127.0.0.1 -n 2 > nul to avoid busy waiting. This line will make your code "wait" for one second between two iterations. Consider that to adjust the waiting time you'll have to replace 2 by the desired amount of seconds to wait +1. So if you want to wait for five seconds the code would be ping 127.0.0.1 -n 6 > nul.

%ERRORLEVEL% is not working incase multiple commands on a Single line

I am trying the below commands and want to get exit of my process(%ERRORLEVEL%). But it is returning previous(last) executed exit code result of sample.exe. I want to get exit code of current command. My requirement is to execute multiple commands in single line*(not batch script)*.
Command:
cmd /c sample.bat "test" > c:\ouput.log & echo %ERRORLEVEL% > c:\returnCode.log
I even tried using "setlocal enableDelayedExpansion" like below. Still It is not returning the exit code of current command
cmd /c setlocal enableDelayedExpansion & sample.bat "test" > c:\ouput.log & echo %ERRORLEVEL% > c:\returnCode.log
Please let me know the way to get current command's exit code.
This should work:
cmd /V:ON /c sample.exe "test" > c:\ouput.log ^& echo !ERRORLEVEL! ^> c:\returnCode.log
/V:ON switch have the same effect of setlocal EnableDelayedExpansion. For further details, type: cmd /?
EDIT: Small error fixed, the & character must be escaped with ^, otherwise, the echo !ERRORLEVEL! command is not executed in the cmd /V:ON !!!
EDIT: Escaping the echo redirection via ^> causes just that echo to be piped into the log. If you do not escape that, the entire command is piped there, i.e. including the stdout stream from "sample.exe".
cmd /c sample.exe "test" > c:\ouput.log & call echo %%ERRORLEVEL%% > c:\returnCode.log
Should work for you. See endless SO items related to delayedexpansion
Thank for your response. I am able to get the exit code of current executed command with below command, only when I run through WMI class(Win32_Process). Using WMI client, I am executing the below command on Remote machine and it is working fine i.e. able to write exit code in Retrun.txt
Command:
cmd /V:ON /c sample.bat "test" > c:\Output.txt & echo !ERRORLEVEL! > c:\Return.txt
But if I run the same command in command prompt of the same remote machine, it is printing "!ERRORLVEL!" in Return.txt instead of "sample.bat" exit code.
I am curious to know why it is not working if I run from Command prompt of the same machine locally.

Resources