I have a problem concerning a C#-program using wmi.
I want this program (as a window-service) to look all the
time, if the sql-server is still running or not.
If it has been quitted, some action shall take place.
So I need a WMI, which is listening all the running
services in a simple way, that I can easily check if sql
is among them.
My first try looks like this:
//get services
System.Management.ObjectQuery
oQuery = new System.Management.ObjectQuery("select Name
from CIM_Service");
//Execute the query
ManagementObjectSearcher oSearcher
= new ManagementObjectSearcher(oQuery);
//Get the results
ManagementObjectCollection
oReturnCollection = oSearcher.Get();
//loop through found services
foreach( ManagementObject oReturn
in oReturnCollection )
{
//Service name
Console.WriteLine ("Name : " +
oReturn["Name"] );
}
I'm sure that there is a better way, isn't it?
Could anybody give me a hint,please?
Best regards and many thanks,
Torben Schulz
{
private ManualResetEvent mre = new ManualResetEvent(false);
public void Run()
{
try
{
WqlEventQuery query = new WqlEventQuery("__InstanceModificationEvent");
query.WithinInterval = new TimeSpan(0, 0, 2); //Ask WMI to poll for
update every 2 seconds. Adjust as necessary
query.Condition = "TargetInstance ISA 'Win32_Service' AND
TargetInstance.Name='Alerter' AND TargetInstance.State='Stopped'";
Console.WriteLine("WMI event query to be executed:\n{0}",
query.QueryString);
ManagementEventWatcher watcher = new ManagementEventWatcher(query);
watcher.EventArrived += new
EventArrivedEventHandler(this.MyEventArrivedHandler);
watcher.Start();
Console.WriteLine("Listening to service event...");
this.mre.WaitOne();
watcher.Stop();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
public void MyEventArrivedHandler(object sender, EventArrivedEventArgs arg)
{
try
{
ManagementBaseObject o =
(ManagementBaseObject)arg.NewEvent["TargetInstance"];
Console.WriteLine("State of {0} service: {1}.", o["Name"],
o["State"]);
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
this.mre.Set();
}
}
}
--
Andy Cheung
Microsoft WMI Test Engineer
This posting is provided "As Is" with no warranties, and confers no rights.
Use of included script samples are subject to the terms specified at
http://www.microsoft.com/info/cpyright.htm
"Torben Schulz" <grim...@gmx.net> wrote in message
news:046001c2f81a$dc528970$a201...@phx.gbl...
thank you very much for the snippet, it was very helpful.
Torben Schulz
"Andy Cheung [MSFT]" <ha...@online.microsoft.com> schrieb im Newsbeitrag
news:OJgX5cD#CHA....@TK2MSFTNGP10.phx.gbl...