Search code examples
windowsbatch-filebackground-process

Windows batch file using start not placing multiple programs in background


I am trying to get data from a sql server and ldap server for multiple clients. I need to get the sql data first and then the ldap data. In Unix shell it was straight forward to make a loop around a sub process with both retrievals going on for each client and then wait for it to complete. As a windows batch file however it happens sequentially. I.e. until I retrieve the data for one client, it won't go to the next. How can I get each client's data simultaneously? Here's what I have:

REM Get DB and client info. from config file
for /F "tokens=1,2,3,4,5,6 delims=| eol=#" %%G in (%cfg%\%env%.data) do (
    REM Mark file as being in process of receiving data
    type nul > %%K.tmp

    REM Get data and remove tmp file to indicate completion
    start cmd /C sqlcmd .... -Q "A long query" ^> %%K.dat1 && "c:\Program Files\Softerra\LDAP Administrator 4\laimex.exe" ... /sql "Another query" > %%K.dat2 && del %%K.tmp
)

For some reason, I need to do the first redirect escaped as ^> while the later one doesn't need that. At this point I am assuming that everything will be retrieved in the background and that I will need to check afterwards for when the processes are complete which I would do by checking the existence of the zero byte temp files I create. What happens though is that each iteration through the loop only starts when the prior one completes rather than occurring straight away by being placed in the background. Can anyone suggest how I can fix this?


Solution

  • You need to escape the && as well (^&^&), otherwise it executes everything after it as soon as start is fired. Example:

    1 gets executed in a new shell correctly, while 2 takes over the main window (not what you want).

    start cmd /C ping 127.0.0.1 && ping 127.0.0.2
    

    Both get executed one after the other in a new window.

    start cmd /C ping 127.0.0.1 ^&^& ping 127.0.0.2
    

    Same as above, another way to do it.

    start cmd /C "ping 127.0.0.1 && ping 127.0.0.2"
    

    Also escape the other >'s, this might work:

    start cmd /C sqlcmd .... -Q "A long query" ^> %%K.dat1 ^&^& "c:\Program Files\Softerra\LDAP Administrator 4\laimex.exe" ... /sql "Another query" ^> %%K.dat2 ^&^& del %%K.tmp