Foreach循环无法将char转换为System.Management.ManagementObject?

时间:2019-06-07 16:07:58

标签: c# wmi

我有一个foreach循环,该循环遍历所有WMI服务,该服务仅查找某些包含要包含和排除的特定关键字的服务。因此,您可以停止某些包含包含和排除单词的服务。不幸的是,我在foreach循环上收到此错误,指出无法将类型'char'转换为'System.Management.ManagementObject'。希望你们知道。感谢您的帮助。

public static void Test()
{
    string include = "SQL";
    string exclude = "EXPRESS, Writer";
    string[] includeArray = include.Split(',');
    string[] excludeArray = exclude.Split(',');

    ConnectionOptions options = new ConnectionOptions();

    //Scope that will connect to the default root for WMI
    ManagementScope theScope = new ManagementScope(@"root\cimv2");

    //Path created to the services with the default options
    ObjectGetOptions option = new ObjectGetOptions(null, TimeSpan.MaxValue, true);
    ManagementPath spoolerPath = new ManagementPath("Win32_Service");
    ManagementClass servicesManager = new ManagementClass(theScope, spoolerPath, option);
    using (ManagementObjectCollection services = servicesManager.GetInstances())
    {
        foreach (ManagementObject item in services.ToString().Where(x => includeArray.ToList().Any(a => x.ToString().Contains(a)) && !excludeArray.Any(a => x.ToString().Contains(a))))
        {
            if (item["Started"].Equals(true))
            {
                item.InvokeMethod("StopService", null);
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您不能在这样的WMI对象上使用Linq。

您可以做的是遍历服务并检查名称:请注意,我还删除了exclude变量中的多余空间。

void Main()
{
    string include = "SQL";
    string exclude = "EXPRESS,Writer";
    string[] includeArray = include.Split(',');
    string[] excludeArray = exclude.Split(',');

    ConnectionOptions options = new ConnectionOptions();

    //Scope that will connect to the default root for WMI
    ManagementScope theScope = new ManagementScope(@"root\cimv2");

    //Path created to the services with the default options
    ObjectGetOptions option = new ObjectGetOptions(null, TimeSpan.MaxValue, true);
    ManagementPath spoolerPath = new ManagementPath("Win32_Service");
    ManagementClass servicesManager = new ManagementClass(theScope, spoolerPath, option);
    using (ManagementObjectCollection services = servicesManager.GetInstances())
    {
        foreach (ManagementObject item in services)
        {
            var serviceName = item["Name"];
            if (includeArray.Any(a => serviceName.ToString().Contains(a)) && !excludeArray.Any(a => serviceName.ToString().Contains(a)))
            {
                if (item["Started"].Equals(true))
                {
                    item.InvokeMethod("StopService", null);
                }
            }
        }
    }
}

答案 1 :(得分:0)

如果要使用Collections以便可以轻松使用Linq,则可以使用ORMi

var list = helper.Query("select * from Win32_Service").ToList().Where(p => p.Contains("reserverWord"));