代码之家  ›  专栏  ›  技术社区  ›  user584018

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

  •  2
  • user584018  · 技术社区  · 7 年前

    使用下面的WMI查询,我可以获得所有服务名称,

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

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

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

    除了WMI还有其他方法吗?

    3 回复  |  直到 7 年前
        1
  •  2
  •   H. Senkaya    7 年前

    我将创建一个批处理文件,用C#触发该文件并捕获返回值 在列表中。

    我的批次。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();
    
        2
  •  2
  •   Marc Wittmann    7 年前

    服务控制器。获取服务 方法

    通常,您可以通过 过程获取进程 方法但文件中指出:

    可以在服务主机进程(svchost.exe)的同一实例中加载多个Windows服务。GetProcess不识别这些单独的服务;为此,请参阅GetServices。

    所以我建议你用这个来检查过程

    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

        3
  •  1
  •   mrogal.ski    7 年前

    您可以使用与之前相同的代码列出所有服务,然后只需迭代它们并检查它们是否正确 PathName 有点像 "C:\WINDOWS\system32\svchost.exe ... " . 那将是最简单的方法。

    另一种选择是将查询重写为以下内容:

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