views:

593

answers:

5

I'm trying to restart the service from a remote machine. Here is my code. The problem is that I need to enter startinfo.filename = "sc.exe" since I'm putting "start /wait sc" this is causing an error. Here is my code, any thoughts. Also if anyone has any idea how to keep the cmd window open after this is ran so I could see the code that was ran that would be awesome.

string strCommandStop1;
string strCommandStop2;
string strCommandStart1;
string strCommandStart2;
string strServer = "\\" + txtServerName.Text;
string strDb1 = "SqlAgent$" + txtInsName.Text;
string strDb2 = "MSSQL$" + txtInsName.Text;

strCommandStop1 = @"start /wait sc " + strServer + " Stop " + strDb1;
strCommandStop2 = @"start /wait sc " + strServer + " Stop " + strDb2;
strCommandStart1 = @"start /wait sc " + strServer + " Start " + strDb2;
strCommandStart2 = @"start /wait sc " + strServer + " Start " + strDb1;

try
{
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.CreateNoWindow = true;

    startInfo.Arguments = strCommandStop1;
    startInfo.Arguments = strCommandStop2;
    startInfo.Arguments = strCommandStart1;
    startInfo.Arguments = strCommandStart2;
    startInfo .FileName = "sc.exe";

    Process.Start(startInfo);

}
catch (Exception e)
{
    MessageBox.Show(e.Message);
}
A: 

"start" is an intrinsic command in the cmd.exe shell, so use cmd.exe as Filename;

ProcessStartInfo si = new ProcessStartInfo();
si.CreateNoWindow = true;
si.Arguments = "/c start /wait sc.exe " + server + " Stop " + database;
si.FileName = "cmd.exe";
Process.Start(si);

Also, your successive re-assignment of the Arguments property looks strange. You need to call Process.Start for each command-line you want to execute.

Kim Gräsman
A: 

I think your problem is that your startInfo object is going to actually call:

sc.exe start /wait sc <strServer> Start <strDb1>

Also, is there a particular requirement you have to use sc instead of using the ServiceController class from the System.ServiceProcess library?

chsh
+2  A: 

Why don't you use the ServiceController class? This way you would have much better control of what is going on.

Stefan Egli
A: 

Thanks everyone I went with using the ServiceController class and that made everything so much easier. Thanks for all your help. J

Jason
A: 

The console can remain open if you use cmd /k and without the start which seems to open a new cmd. so it should be something like cmd /k sc.exe " + server + " Stop " + database;

Adrian Pascalin