Reputation: 11
I have a foreach loop that loops through all WMI services which only looks for certain services that contains specific key words to include and exclude. Therefore you can stop certain services that contains the included and excluded words. Unfortunately I'm receiving this error on the foreach loop that states Cannot convert type 'char' to 'System.Management.ManagementObject'. Hopefully you guys know. Thanks for the help.
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);
}
}
}
}
Upvotes: 0
Views: 541
Reputation: 73313
You can't use Linq on WMI objects like that.
What you can do is loop over the services and check the name: note also I removed the extra space in the exclude
variable.
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);
}
}
}
}
}
Upvotes: 1