2017-10-05 59 views
1

使用下面的WMI查询我能够得到所有服务的名称上运行的所有服务的名称,如何获得,根据“中svchost.exe”进程

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

而且,当我在命令提示符下运行以下命令,它会给所有的进程ID(PID)和服务名称,

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

我想WMI/C#的方式找到所有这下“的svchost.exe”进程中运行的服务?

除了WMI还有其他方法吗?

+0

我认为你正在寻找一个比较难看的解决方案,基本上你最终使用电话(非托管)的DLL PInvoke的。我认为你需要的ABI参考是在https://msdn.microsoft.com/en-us/library/aa394418(v=vs.85).aspx。它可能会减少调用一个麻烦PowerShell脚本或在后台的东西。 – BurnsBA

+1

更好的问题:你对这些信息做了什么?根据这一点,甚至可能比获得现在获得的更简单/更好的方法。 –

回答

1

你可以使用和你一样的代码列出所有的服务,然后遍历它们并检查它们的PathName是否与"C:\WINDOWS\system32\svchost.exe ... "类似。这将是最简单的方法。

另一种选择是将您的查询改写成这样:

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

我想创建一个批处理文件,我触发与C#,赶上列表的返回值 。

的解决方案可能是这样的:

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

怎么样ServiceController.getServices方法?

通常情况下,您将通过Process.GetProcesses方法获取流程。虽然文档状态如下:

多个Windows服务可以在服务主机进程(svchost.exe)的同一实例中加载。 GetProcesses不识别那些单独的服务;为此,请参阅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

相关问题