如何获取在 "svchost.exe" 进程下运行的所有服务名称

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

使用下面的 WMI 查询我能够获取所有服务名称,

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

此外,当我在命令提示符下 运行 下面的命令时,它会给出所有进程 ID (PID) 和服务名称,

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

我想要 WMI/C# 找到在 "svchost.exe" 进程下运行的所有服务的方法?

除了WMI还有其他方法吗?

您可以使用与之前相同的代码列出所有服务,然后遍历它们并检查它们的 PathName 是否类似于 "C:\WINDOWS\system32\svchost.exe ... "。那将是最简单的方法。

另一种选择是将您的查询重写为如下形式:

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

我会创建一个批处理文件,我用 C# 触发并捕获 return 值 的名单。

解决方案可能如下所示:

myBatch.bat:

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

C#程序:

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

ServiceController.getServices方法怎么样?

通常您会通过 Process.GetProcesses 方法获取流程。文档指出:

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.

如果您需要有关服务的更多信息,您必须依赖 WMI,而不是循环访问它们。

所以我建议您使用它来检查流程

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