WMI Question

J

John

Hi, I have the following code:
WqlEventQuery query = new WqlEventQuery();

query.EventClassName = "__InstanceOperationEvent";

query.WithinInterval = new TimeSpan(0, 0, 1);

query.Condition = "TargetInstance ISA \"Win32_Service\" AND
TargetInstance.Name = \"CentennialClientAgent\"";

watcher = new ManagementEventWatcher(query);

watcher.EventArrived += new EventArrivedEventHandler(this.Arrived);

watcher.Start();

private void Arrived(object sender, EventArrivedEventArgs e) {

ManagementBaseObject o =
(ManagementBaseObject)e.NewEvent["TargetInstance"];

System.Diagnostics.Debug.WriteLine(o["Started"].ToString());

System.Diagnostics.Debug.WriteLine(o["StartMode"].ToString());

//TODO: how do I get the instance and invoke the method - such as
StopService()

}

My question is how can I get the ManagementObject from the
ManagementBaseObject? because what I wanted to do is to invoke a method on
that instance - only ManagementObject has invokemethod.

Thanks!

John
 
W

Willy Denoyette [MVP]

You need to create an instance of the ManagementObject using the Service
"Name" property.
Something like this will do....

....
// Check if started
if((bool)o["Started"] == true)
{
StopService(mbo["Name"].ToString());
}
....

public void StopService(string ServiceName)
{
ManagementPath myPath = new ManagementPath();
myPath.Server = System.Environment.MachineName;
myPath.NamespacePath = @"root\CIMV2";
myPath.RelativePath = "Win32_Service.Name='" + ServiceName + "'";
using (ManagementObject nac= new ManagementObject(myPath))
{
ManagementBaseObject outParams = nac.InvokeMethod("StopService", null,
null);
.....


Willy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top