Sunday, July 5, 2015

batch file - Pause command is run out of order when running "start cmd /c" multiple times



I have a script like this:



@start /b cmd /c net stop "Service"

@start /b cmd /c net stop "Service"
@start /b cmd /c net stop "Service"
@start /b cmd /c net stop "Service"
@start /b cmd /c net stop "Service"
pause


However, the pause command gets executed before all of the lines above it in the script have been executed. I need to use @start /b cmd /c so that it doesn't have to wait for the "Stopping Service..." after each service (about 100) of time. Is there any way to tell cmd to wait until all of the @start /b cmd /c net stop "Service" commands have completed then run the pause?



To see what I'm talking about run this batch file:




@start /b cmd /c echo Hello
@start /b cmd /c echo Hello
@start /b cmd /c echo Hello
@start /b cmd /c echo Hello
@start /b cmd /c echo Hello
@start /b cmd /c echo Hello
pause



Instead of the Pause occurring after all of the Hello have been printed, it happens in the middle:



enter image description here


Answer



The command start starts an aplication in it's own context, appart from what you current console is doing, that's why when it's done it will return the output, once your current terminal is done with whatever is doing. That's why even though you send all this start command, your pause is not waiting for all of them to finish It's just waiting long enough to start the processes, That's why your pause appears in the midle of them it's just a thing of timing.



So to solve you problem you can wait for them to finish with /wait or making a call to a second batch script, this way you can wait for some commands and not others, if you preffer:



Wait technique for your script




@start /wait /b cmd /c echo Hello
@start /wait /b cmd /c echo Hello
@start /wait /b cmd /c echo Hello
@start /wait /b cmd /c echo Hello
@start /wait /b cmd /c echo Hello
@start /wait /b cmd /c echo Hello
pause


Technique with laucher script




@echo off
title Laucher

:: This scripts don't need to be waited
start /b cmd /c 'script1.bat'
:: This script needs to be waited
start /wait /b cmd /c 'script2.bat'



Script1



@echo off
title Script to run without waiting

SomeProcessThatDoesn'tNeedsToBeWaited


Script2




@echo off
title Script to run to be waited

SomeProcessThatNeedsToBeWaited


cheers


No comments:

Post a Comment

linux - How to SSH to ec2 instance in VPC private subnet via NAT server

I have created a VPC in aws with a public subnet and a private subnet. The private subnet does not have direct access to external network. S...