I have a Windows Service which I install using the InstallUtil.exe. Even though I have set the Startup Method to Automatic, the service does not start when installed, I have to manually open the services and click start. Is there a way to start it either via the command line, or through the code of the Service?
Automatic startup means that the service is automatically started when Windows starts. As others have mentioned, to start it from the console you should use the ServiceController.
How about following commands?
net start "<service name>"
net stop "<service name>"
You can use the following command line to start the service:
net start *servicename*
Use ServiceController to start your service from code.
Update: And more correct way to start service from the command line is to use "sc" (Service Controller) command instead of "net".
You can use the GetServices
method of ServiceController
class to get an array of all the services. Then, find your service by checking the ServiceName
property of each service. When you've found your service, call the Start
method to start it.
You should also check the Status
property to see what state it is already in before calling start (it may be running, paused, stopped, etc..).
Programmatic options for controlling services:
- Native code can used, "Starting a Service". Maximum control with minimum dependencies but the most work.
- WMI: Win32_Service has a
StartService
method. This is good for cases where you need to be able to perform other processing (e.g. to select which service). - PowerShell: execute
Start-Service
viaRunspaceInvoke
or by creating your ownRunspace
and using itsCreatePipeline
method to execute. This is good for cases where you need to be able to perform other processing (e.g. to select which service) with a much easier coding model than WMI, but depends on PSH being installed. - A .NET application can use
ServiceController
In your Installer class, add a handler for the AfterInstall event. You can then call the ServiceController in the event handler to start the service.
public ServiceInstaller()
{
//... Installer code here
this.AfterInstall += new InstallEventHandler(ServiceInstaller_AfterInstall);
}
void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
{
ServiceController sc = new ServiceController("ServiceName");
sc.Start();
}
Now when you run InstallUtil on your installer it will install and then start up the service.
Thank you for this code espressoplace. It is precisely what I was looking for. :)