C# 查询 Windows 服务 [英] C# Query Windows Service

查看:46
本文介绍了C# 查询 Windows 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用一个应用程序来查询远程服务器上运行的 Windows 服务,并将机器名称、服务名称和状态写入数据库.

I have been using an application that queries Windows Services running on remote servers and writes the Machine Name, Service Name, and Status to a database.

但是,我也想尝试捕获启动类型(自动、手动、禁用).我使用的服务控制器没有任何启动类型选项,所以我开始考虑使用管理类.这个类看起来有我需要的一切,但我不知道如何在我的远程服务器上使用它.对于服务控制器,我是这样做的:

However, I want to try and capture the startup type (Automatic, Manual, Disabled) as well. I was using a Service Controller which does not have any options for startup type so I started looking at using a Management Class. This class looks like it has everything I need but I don't know how to use it against my remotes servers. For the Service Controller, I was doing this:

ServiceController[] services = ServiceController.GetServices(serverIP);

foreach (ServiceController service in services)
{
   var machine = service.MachineName;
   var displayName = service.DisplayName;
   var status = service.Status;
}

我在管理类中尝试了这个:

I tried this for the Management class:

ManagementClass class1 = new ManagementClass(serverIP + "\\" + "Win32_Service");

foreach (ManagementObject ob in class1.GetInstances())
{
   var machine = serverIP;
   var displayName = ob.GetPropertyValue("Description");
   var name = ob.GetPropertyValue("PathName");
   var startMode = ob.GetPropertyValue("StartMode");
   var status = ob.GetPropertyValue("State");
}

但当然没用.任何人都知道如何使用管理类从远程机器获取服务?或者有没有其他方法使用Service Controller获取启动类型?

But of course it didn't work. Anyone know how I can get the Services from a remote machine using the Management Class? Or is there another way using the Service Controller to get the startup type?

我也尝试将它们结合起来,并将管理类 foreach 语句放在服务控制器中,但它陷入了无限循环.

I also tried to combine them both and put the Management Class foreach statement inside the Service Controller but it got stuck in an endless loop.

推荐答案

上述相同的代码有效.只需将此添加到管理类

The same code above worked. Just add this to Management Class

(@"\\" + serverIP + "\\root\\cimv2:Win32_Service")

这篇关于C# 查询 Windows 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆