Остановка службы

4 метода для остановки службы
C#:
  foreach (ServiceController Svc in ServiceController.GetServices())
    {
        using (Svc)
        {
            //The short name of "Microsoft Exchange Service Host"
            if (Svc.ServiceName.Equals("YourServiceName"))
            {
                if (Svc.Status != ServiceControllerStatus.Stopped)
                {
                    if (Svc.CanStop)
                    {
                        try
                        {
                            Svc.Stop();
                            Svc.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 15));
                        }
                        catch
                        {
                            //Try to stop using Process
                            foreach (Process Prc in Process.GetProcessesByName(Svc.ServiceName))
                            {
                                using (Prc)
                                {
                                    try
                                    {
                                        //Try to kill the service process
                                        Prc.Kill();
                                    }
                                    catch
                                    {
                                        //Try to terminate the service using taskkill command
                                        Process.Start(new ProcessStartInfo
                                        {
                                            FileName = "cmd.exe",
                                            CreateNoWindow = true,
                                            UseShellExecute = false,
                                            Arguments = string.Format("/c taskkill /pid {0} /f", Prc.Id)
                                        });

                                        //Additional:
                                        Process.Start(new ProcessStartInfo
                                        {
                                            FileName = "net.exe",
                                            CreateNoWindow = true,
                                            UseShellExecute = false,
                                            Arguments = string.Format("stop {0}", Prc.ProcessName)
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
 
C#:
public static void Kill()
    {
        int processId = GetProcessIdByServiceName(ServiceName);

        var process = Process.GetProcessById(processId);
        process.Kill();
    }

    private static int GetProcessIdByServiceName(string serviceName)
    {

        string qry = $"SELECT PROCESSID FROM WIN32_SERVICE WHERE NAME = '{serviceName }'";
        var searcher = new ManagementObjectSearcher(qry);
        var managementObjects = new ManagementObjectSearcher(qry).Get();

        if (managementObjects.Count != 1)
            throw new InvalidOperationException($"In attempt to kill a service '{serviceName}', expected to find one process for service but found {managementObjects.Count}.");

        int processId = 0;

        foreach (ManagementObject mngntObj in managementObjects)
            processId = (int)(uint) mngntObj["PROCESSID"];

        if (processId == 0)
            throw new InvalidOperationException($"In attempt to kill a service '{serviceName}', process ID for service is 0. Possible reason is the service is already stopped.");

        return processId;
    }
 
Проверяет, существует ли служба, если она «Отключена», она устанавливает для службы значение «Авто», и когда она не может перезапустить службу, она будет использовать команду taskkill, чтобы убить службу через PID, а затем запустить ее снова (Вы должны быть осторожны с зависимыми службы с этой причиной, вам также нужно будет запустить/перезапустить их).

И он просто возвращает true/false, если перезагрузка прошла успешно.

Проверено только на WIN10.
C#:
//Get windows service status
    public static string GetServiceStatus(string NameOfService)
    {
        ServiceController sc = new ServiceController(NameOfService);

        switch (sc.Status)
        {
            case ServiceControllerStatus.Running:
                return "Running";
            case ServiceControllerStatus.Stopped:
                return "Stopped";
            case ServiceControllerStatus.Paused:
                return "Paused";
            case ServiceControllerStatus.StopPending:
                return "Stopping";
            case ServiceControllerStatus.StartPending:
                return "Starting";
            default:
                return "Status Changing";
        }
    }

    //finds if service exists in OS
    public static bool DoesServiceExist(string serviceName)
    {
        return ServiceController.GetServices().Any(serviceController => serviceController.ServiceName.Equals(serviceName));
    }

    //finds startup type of service
    public static string GetStartupType(string serviceName)
    {
        ManagementObject objManage = new ManagementObject("Win32_Service.Name='"+serviceName+"'");
        objManage.Get();

        string status1 = objManage["StartMode"].ToString();

        return status1;
    }

    //restart service through PID
    public static bool RestartServiceByPID(string NameOfService)
    {
        LogWriter log = new LogWriter("TaskKilling: " + NameOfService);

        string strCmdText = "/C taskkill /f /fi \"SERVICES eq " + NameOfService + "\"";
        Process.Start("CMD.exe", strCmdText);

        using(ServiceController ScvController = new ServiceController(NameOfService))
        {
            ScvController.WaitForStatus(ServiceControllerStatus.Stopped);

            if (GetServiceStatus(NameOfService) == "Stopped")
            {
                ScvController.Start();
                ScvController.WaitForStatus(ServiceControllerStatus.Running);

                if (GetServiceStatus(NameOfService) == "Running")
                {
                    return true;
                }
                else
                {
                    return false;
                }

            }
            else
            {
                return false;
            }
        }
    }

    //Restart windows service
    public static bool RestartWindowsService(string NameOfService)
    {

        try
        {
            //check if service exists
            if(DoesServiceExist(NameOfService) == false)
            {
                MessageBox.Show("Service " + NameOfService + " was not found.");
                return false;
            }
            else
            {
                //if it does it check startup type and if it is disabled it will set it to "Auto"
                if (GetStartupType(NameOfService) == "Disabled")
                {
                    using (var svc = new ServiceController(NameOfService))
                    {
                        ServiceHelper.ChangeStartMode(svc, ServiceStartMode.Automatic);

                        if (svc.Status != ServiceControllerStatus.Running)
                        {
                            svc.Start();
                            svc.WaitForStatus(ServiceControllerStatus.Running);

                            if(GetServiceStatus(NameOfService) == "Running")
                            {
                                return true;
                            }
                            else
                            {
                                return false;
                            }
                        }
                        else
                        {
                            svc.Stop();
                            svc.WaitForStatus(ServiceControllerStatus.Stopped);

                            if(GetServiceStatus(NameOfService) == "Stopped")
                            {
                                svc.Start();
                                svc.WaitForStatus(ServiceControllerStatus.Running);

                                if(GetServiceStatus(NameOfService) == "Running")
                                {
                                    return true;
                                }
                                else
                                {
                                    return false;
                                }
                            }
                            //restart through PID
                            else
                            {
                                return RestartServiceByPID(NameOfService);
                            }
                        }

                    }
                }
                //If service is not disabled it will restart it
                else
                {
                    using(ServiceController ScvController = new ServiceController(NameOfService))
                    {
                        if(GetServiceStatus(NameOfService) == "Running")
                        {

                            ScvController.Stop();
                            ScvController.WaitForStatus(ServiceControllerStatus.Stopped);

                            if(GetServiceStatus(NameOfService) == "Stopped")
                            {
                                ScvController.Start();
                                ScvController.WaitForStatus(ServiceControllerStatus.Running);

                                if(GetServiceStatus(NameOfService) == "Running")
                                {
                                    return true;
                                }
                                else
                                {
                                    return false;
                                }

                            }
                            //if stopping service fails, it uses taskkill
                            else
                            {
                                return RestartServiceByPID(NameOfService);
                            }
                        }
                        else
                        {
                            ScvController.Start();
                            ScvController.WaitForStatus(ServiceControllerStatus.Running);

                            if(GetServiceStatus(NameOfService) == "Running")
                            {
                                return true;
                            }
                            else
                            {
                                return false;
                            }

                        }
                    }
                }
            }
        }
        catch(Exception ex)
        {
            return RestartServiceByPID(NameOfService);
        }
    }
 
Back
Top