How to get all services name that runs under “svchost.exe” process

扶醉桌前 提交于 2021-02-08 02:59:35

问题


Using below WMI query I am able to get all services names,

ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_Service ")

Also, when I'm running below command in command prompt, it will give all the Process Id (PID) and Service Name,

tasklist /svc /fi "imagename eq svchost.exe" 

I want WMI/C# way to find all the service which runs under "svchost.exe" process?

And Is there any other way other than WMI?


回答1:


You can list all of the services using the same code as you did and then just iterate through them and check if their PathName is something like "C:\WINDOWS\system32\svchost.exe ... ". That would be the easiest way.

Another option would be to rewrite your query into something like this :

string q = "select * from Win32_Service where PathName LIKE \"%svchost.exe%\"";
ManagementObjectSearcher mos = new ManagementObjectSearcher(q);



回答2:


I would create a batch-file which I trigger with C# and catch the return value of the list.

The solution could look like this:

myBatch.bat:

tasklist /svc /fi "IMAGENAME eq svchost.exe"

C# program:

 Process p = new Process();
 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardOutput = true;
 p.StartInfo.FileName = "myBatch.bat";
 p.Start();
 string output = p.StandardOutput.ReadToEnd();
 Console.Write(output);
 p.WaitForExit();



回答3:


How about the ServiceController.getServices method?

Normally you would get the processes via the Process.GetProcesses method. The documentation states though:

Multiple Windows services can be loaded within the same instance of the Service Host process (svchost.exe). GetProcesses does not identify those individual services; for that, see GetServices.

If you need more information about the serices, you have to rely on the WMI, but not to iterate through them.

So I would suggest you use this to examine the processes

foreach (ServiceController scTemp in scServices)
{
   if (scTemp.Status == ServiceControllerStatus.Running)
   {
      Console.WriteLine("  Service :        {0}", scTemp.ServiceName);
      Console.WriteLine("    Display name:    {0}", scTemp.DisplayName);

     // if needed: additional information about this service.
     ManagementObject wmiService;
     wmiService = new ManagementObject("Win32_Service.Name='" +
     scTemp.ServiceName + "'");
     wmiService.Get();
     Console.WriteLine("    Start name:      {0}", wmiService["StartName"]);
     Console.WriteLine("    Description:     {0}", wmiService["Description"]);
   }
}

Source



来源:https://stackoverflow.com/questions/46588575/how-to-get-all-services-name-that-runs-under-svchost-exe-process

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!