Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait until my batch file is finished

I'm doing a program where I need to start cmd and there start up a batch file. The problem is that I'm using MyProcess.WaithForexit(); and I think it does not wait until the batch file processing is finished. It just waits until the cmd is closed. My code so far:

System.Diagnostics.ProcessStartInfo ProcStartInfo =
    new System.Diagnostics.ProcessStartInfo("cmd");
    ProcStartInfo.RedirectStandardOutput = true;
    ProcStartInfo.UseShellExecute = false;
    ProcStartInfo.CreateNoWindow = false;
    ProcStartInfo.RedirectStandardError = true;
    System.Diagnostics.Process MyProcess = new System.Diagnostics.Process();
    ProcStartInfo.Arguments = "/c start batch.bat ";
    MyProcess.StartInfo = ProcStartInfo;
    MyProcess.Start();
    MyProcess.WaitForExit();

I need to wait until the batch file is finished. How do I do that?

like image 787
Manuel Sebastian Rios Avatar asked Jun 06 '15 12:06

Manuel Sebastian Rios


People also ask

How do I set a batch timeout?

Timeout with the parameter /NOBREAK If we take the example from before and run that in a BATCH file: timeout /t 60 then while waiting those 60 seconds, you are actually able to break the timeout by pressing any key on your keyboard. To prevent this we simply add the parameter /NOBREAK to the end of it.

What is timeout in batch file?

Pauses the command processor for the specified number of seconds. This command is typically used in batch files.

How do I pause a batch script?

Execution of a batch script can also be paused by pressing CTRL-S (or the Pause|Break key) on the keyboard, this also works for pausing a single command such as a long DIR /s listing. Pressing any key will resume the operation. Pause is often used at the end of a script to give the user time to read some output text.

How do you put a batch file to sleep?

The correct way to sleep in a batch file is to use the timeout command, introduced in Windows 2000.


2 Answers

This actually worked just fine for me:

System.Diagnostics.Process.Start("myBatFile.bat").WaitForExit();

As milton said, adding 'exit' at the end of your batch files is most likely a good idea.

Cheers

like image 55
HarvesteR Avatar answered Nov 14 '22 23:11

HarvesteR


The start command has arguments that can make it WAIT for the started program to complete. Edit the arguments as show below to pass '/wait':

ProcStartInfo.Arguments = "/c start /wait batch.bat ";

I would also suggest that you want your batch file to exit the cmd envirionment so place an 'exit' at the end of the batch.

@echo off
rem Do processing
exit

This should achieve the desired behavior.

like image 23
miltonb Avatar answered Nov 14 '22 21:11

miltonb