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

Foreach loop Cannot convert char to System.Management.ManagementObject?

我有一个循环遍历所有 WMI 服务的 foreach 循环,它只查找包含要包含和排除的特定关键字的某些服务。因此,您可以停止某些包含包含和排除的词的服务。不幸的是,我在 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);
            }
        }
    }
}

您不能像那样在 WMI 对象上使用 Linq。

你可以做的是遍历服务并检查名称:另请注意,我删除了 exclude 变量中的额外 space。

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

如果您想使用 Collections 以便轻松使用 Linq,您可以使用 ORMi

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