Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to autostart windows service after install by sc?

I created a batch file for installing service because I need to install my service on PC don't have Visual Studio.

Content of batch file:

@echo OFF
echo Installing service...
sc create "MyService" binpath= %~dp0\MyService.exe start= auto
echo Installing service complete
pause

And I need to autostart MyService after install, so I make this code:

private void svInstaller_AfterInstall(object sender, InstallEventArgs e)
{
    ServiceController sc = new ServiceController(svInstaller.ServiceName);
    sc.Start();
}

Don't any problem if I installing my service by Visual Studio Command Prompt with InstallUtil. When I install service by batch file, my service didn't autostart.

How to possible to auto start my service after install by batch file?

Update: Thanks Sam Denty's answer, I problem is resolved.
But I have another question: When I install my service by sc, my code in AfterInstall function do not work?

like image 281
Fox Vĩnh Tâm Avatar asked Apr 01 '17 19:04

Fox Vĩnh Tâm


1 Answers

This is possible by using either the net start service or sc start command (see previous question on that).

To start a service using sc start, the syntax is:

sc [<ServerName>] start <ServiceName> [<ServiceArguments>]

<ServerName>
    Specifies the name of the remote server on which the service is located. The name must use the Universal Naming Convention (UNC) format (for example, \\myserver). To run SC.exe locally, omit this parameter.
<ServiceName>
    Specifies the service name returned by the getkeyname operation.
<ServiceArguments>
    Specifies the service arguments to pass to the service to be started.

Example:

sc start MyService


Updated script:

@echo OFF
echo Installing service...
sc create "MyService" binpath= %~dp0\MyService.exe start= auto
sc start MyService
echo Installing service complete
pause
like image 82
Sam Denty Avatar answered Sep 29 '22 19:09

Sam Denty