Oh hi Mark
Oh hi Mark

Reputation: 203

Run multiple commands on command prompt

I am using this code

Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();
cmd.StandardInput.WriteLine("SQLCMD -E -S srvName -Q \"RESTORE DATABASE dbName FROM DISK=\'C:\\app\\dbName_300915_000.bak\'\"");            
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
cmd.WaitForExit();
textBox2.Text = cmd.StandardOutput.ReadToEnd();

to restore a database. My issue here is that I need to run the

cmd.StandardInput.WriteLine("SQLCMD -E -S srvName -Q \"RESTORE DATABASE dbName FROM DISK=\'C:\\app\\dbName_300915_000.bak\'\""); 

multiple times for multiple databases. Do I need to create a different process each time? I could use the cmd.StandardInput.Writeline one after another but I want an update on my textbox after each restore is finished.

Upvotes: 1

Views: 3360

Answers (2)

user3690202
user3690202

Reputation: 4045

You could also just do this, for example:

Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();
cmd.StandardInput.WriteLine("SQLCMD -E -S srvName -Q \"RESTORE DATABASE dbName FROM DISK=\'C:\\app\\dbName_300915_000.bak\'\"");            
cmd.StandardInput.WriteLine("SQLCMD -E -S srvName -Q \"RESTORE DATABASE dbName FROM DISK=\'C:\\app\\dbName_300915_000.bak\'\"");            
cmd.StandardInput.WriteLine("SQLCMD -E -S srvName -Q \"RESTORE DATABASE dbName FROM DISK=\'C:\\app\\dbName_300915_000.bak\'\"");            
cmd.StandardInput.WriteLine("SQLCMD -E -S srvName -Q \"RESTORE DATABASE dbName FROM DISK=\'C:\\app\\dbName_300915_000.bak\'\"");            
cmd.StandardInput.WriteLine("SQLCMD -E -S srvName -Q \"RESTORE DATABASE dbName FROM DISK=\'C:\\app\\dbName_300915_000.bak\'\"");            
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
cmd.WaitForExit();
textBox2.Text = cmd.StandardOutput.ReadToEnd();

Also, your ReadToEnd() is wrong and can potentially cause deadlocks. See MSDN:

// To avoid deadlocks, always read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();

Upvotes: 1

Stuart
Stuart

Reputation: 764

You could create a batch file, either manually or through code, and then execute that batch file from the command prompt.

Process p = new Process();
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = "C:\\cmd.exe";
p.StartInfo.Arguments = @"<location of batch file>\<batch file name>.bat";
p.Start();
p.WaitForExit();

Upvotes: 1

Related Questions