user584018
user584018

Reputation: 11344

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

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?

Upvotes: 2

Views: 3570

Answers (3)

Marc Wittmann
Marc Wittmann

Reputation: 2361

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

Upvotes: 2

H. Senkaya
H. Senkaya

Reputation: 773

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

Upvotes: 2

mrogal.ski
mrogal.ski

Reputation: 5930

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

Upvotes: 1

Related Questions