I want to create a collection of Windows Services that will match a regular expression using a Where
clause.
For example, I have 3 Windows Services called:
RCLoad1
RCLoad2
RCLoad3
my Regex would be something like: "^RCLoad*"
I'd like to use something like:
ServiceController[] myServices = ServiceController.GetServices(ServerName)
.Where Regex.IsMatch(....)
But I can't get it to work.
You are not clear on the exact failure.
Does GetServices(ServerName)
actually return a list of items?
Subsequently you don't mention what property has the name of the server, Is it Name
? Because the code you have now takes the objects ToString()
which most likely defaults to the type name and hence the failure. (?)
Find the right name property and use the pattern RCLoad
, which will find it anywhere in the string, and then put into a ToList()
such as
Regex rgx = new Regex(@"RCLoad"); // RCLoad can be anywhere in the string.
var controllers = ServiceController.GetServices(ServerName)
.Where(sc => rgx.IsMatch( sc.Name ))
.ToList();