C# 如何获取在“下运行的所有服务名称”;svchost.exe“;过程
使用下面的WMI查询,我可以获得所有服务的名称C# 如何获取在“下运行的所有服务名称”;svchost.exe“;过程,c#,wmi,C#,Wmi,使用下面的WMI查询,我可以获得所有服务的名称 ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_Service ") 另外,当我在命令提示符下运行下面的命令时,它将给出所有进程Id(PID)和服务名称 tasklist /svc /fi "imagename eq svchost.exe" 我想要WMI/C#找到在“svchost.exe”进程下运行的所有服务的方法 除了WMI
ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_Service ")
另外,当我在命令提示符下运行下面的命令时,它将给出所有进程Id(PID)和服务名称
tasklist /svc /fi "imagename eq svchost.exe"
我想要WMI/C#找到在“svchost.exe”进程下运行的所有服务的方法
除了WMI,还有其他方法吗?您可以使用与以前相同的代码列出所有服务,然后对它们进行迭代,检查它们的
路径名是否类似于“C:\WINDOWS\system32\svchost.exe…”
。那将是最简单的方法
另一种选择是将查询重写为以下内容:
string q = "select * from Win32_Service where PathName LIKE \"%svchost.exe%\"";
ManagementObjectSearcher mos = new ManagementObjectSearcher(q);
我将创建一个批处理文件,用C#触发该文件并捕获返回值
在名单上
解决方案可能如下所示:
myBatch.bat:
tasklist /svc /fi "IMAGENAME eq svchost.exe"
C#计划:
那么ServiceController.getServices方法呢
通常,您将通过Process.GetProcesses方法获取进程。但文件指出:
可以在服务主机进程(svchost.exe)的同一实例中加载多个Windows服务。GetProcesss不识别那些单独的服务;有关详细信息,请参阅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"]);
}
}
我认为您正在寻找一个相当丑陋的解决方案,基本上您最终会使用pinvoke调用(非托管)DLL。我想你想要的ABI参考是在。在后台调用powershell脚本或其他东西可能不会太麻烦。更好的问题是:你在用这些信息做什么?根据这一点,可能有比现在得到的更简单/更好的方法。
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"]);
}
}