簡體   English   中英

使用taskkill停止Windows服務

[英]Stopping windows service with taskkill

我需要幫助來使用C#殺死一個Windows服務,現在要殺死該服務使用以下選項:

從cmd:

sc queryex ServiceName

在發現服務的PID之后

taskkill /pid 1234(exemple) /f

為了便於閱讀,我將使用單獨的方法IsServiceInstalled,IsServiceRunning,StopService ..etc將服務交互分離到它自己的類中,如果你理解我的意思。

此外,通過停止服務,它應該已經殺死了這個過程,但我也包括了你將如何做這樣的事情。 如果服務不會停止並且您通過終止進程來停止它,那么如果您無法正確構建訪問權限,我會查看服務代碼。

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

如果你知道進程id使用Process.GetProcessById(Id).Kill(); 如果您知道進程名稱,請使用Process.GetProcessesByName(name).Kill();

這里代碼使用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)
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM