正在使用taskkill停止windows服务

本文关键字:停止 windows 服务 taskkill | 更新日期: 2023-09-27 17:57:58

我需要帮助使用C#终止windows服务,现在要终止服务,请使用以下选项:

从cmd:

sc queryex ServiceName

发现服务的PID

taskkill /pid 1234(exemple) /f

正在使用taskkill停止windows服务

为了便于阅读,但我会用单独的方法IsServiceInstalled、IsServiceRunning、StopService将服务交互分离到它自己的类中。。等等,如果你明白我的意思。

同样,通过停止服务,它应该已经终止了进程,但我也包括了如何做这样的事情。如果服务不会停止,而你通过终止进程来停止它,如果你有权访问它,我会查看服务代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceProcess;
using System.Diagnostics;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            ServiceController sc = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName.Equals("MyServiceNameHere"));
            if (sc != null)
            {
                if (sc.Status.Equals(ServiceControllerStatus.Running))
                {
                    sc.Stop();
                    Process[] procs = Process.GetProcessesByName("MyProcessName");
                    if (procs.Length > 0)
                    {
                        foreach (Process proc in procs)
                        {
                            //do other stuff if you need to find out if this is the correct proc instance if you have more than one
                            proc.Kill();
                        }
                    }
                }
            }
        }
    }
}

Process.GetProcessesByName("服务名称")在我的情况下不起作用,但下面的方法起作用。您将需要对System.ServiceProcess和System.Management.的引用

    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;
    }

这里的代码使用4种方法来停止您的服务,包括TaskKill,请注意,您必须有足够的权限才能这样做。

  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)
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

如果您知道进程id使用Process.GetProcessById(Id).Kill();如果您知道进程名称,请使用Process.GetProcessesByName(name).Kill();