using System;
using System.ServiceProcess;
namespace ServiceListApplication
{
public class MyApplication
{
public static void Main(string[] Arguments)
{
string runType = ( Arguments.Length > 0 ) ? Arguments[0] : "";
ServiceController[] ServiceList = ServiceController.GetServices();
for (int i = 0; i < ServiceList.Length; i++)
{
// this makes anything other then "apache2" or "mysql51" continue.
switch (ServiceList[i].ServiceName)
{
case "Apache2":
case "MySQL51":
break;
default:
// continue to the next item in the loop
continue;
break;
}
switch (runType)
{
case "start":
if (ServiceList[i].Status == ServiceControllerStatus.Running)
{
Console.WriteLine(ServiceList[i].ServiceName + " is already running.");
}
else
{
Console.WriteLine("Attempting to start " + ServiceList[i].ServiceName + " service.");
ServiceList[i].Start();
ServiceList[i].WaitForStatus(ServiceControllerStatus.Running);
if (ServiceList[i].Status == ServiceControllerStatus.Running)
{
Console.WriteLine("Started " + ServiceList[i].ServiceName + " successfully.");
}
else
{
Console.WriteLine("Failed to start " + ServiceList[i].ServiceName + " successfully.");
}
}
break;
case "restart":
Console.WriteLine("Attempting to restart " + ServiceList[i].ServiceName + " service.");
if (ServiceList[i].Status == ServiceControllerStatus.Stopped)
{
Console.WriteLine(ServiceList[i].ServiceName + " is currently stopped.");
}
else
{
Console.WriteLine("Attempting to stop the " + ServiceList[i].ServiceName + " service.");
ServiceList[i].Stop();
ServiceList[i].WaitForStatus(ServiceControllerStatus.Stopped);
Console.WriteLine("Stopped the " + ServiceList[i].ServiceName + " service successfully");
}
Console.WriteLine("Attempting to start " + ServiceList[i].ServiceName + " service.");
ServiceList[i].Start();
ServiceList[i].WaitForStatus(ServiceControllerStatus.Running);
if (ServiceList[i].Status == ServiceControllerStatus.Running)
{
Console.WriteLine("Started " + ServiceList[i].ServiceName + " successfully.");
}
else
{
Console.WriteLine("Failed to start " + ServiceList[i].ServiceName + " successfully.");
}
break;
case "stop":
Console.WriteLine("Attempting to stop the " + ServiceList[i].ServiceName + " service.");
ServiceList[i].Stop();
ServiceList[i].WaitForStatus(ServiceControllerStatus.Stopped);
Console.WriteLine("Stopped the " + ServiceList[i].ServiceName + " service successfully");
break;
default:
// No go
Console.WriteLine("Sorry but you must specify a mode when using this application, available modes are 'Start', 'Stop', and 'Restart'.");
Console.WriteLine("... Press any key to continue");
Console.ReadKey();
return;
}
}
Console.WriteLine("... Press any key to continue");
Console.ReadKey();
return;
}
}
}