using
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;
System.Management;
sac;
namespace
sac
{
public partial class Form1 : Form
public Form1()
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
try
ConnectionOptions options = new ConnectionOptions();
options.Username =
"ad.xxx.xxx";
options.Password =
"xxx";
ManagementScope scope = new ManagementScope("\\\\servername\\root\\cimv2", options);
//ManagementPath path = new ManagementPath("Win32_Process");
//ObjectGetOptions o = new ObjectGetOptions(null, new TimeSpan(0, 0, 0, 5), true);
scope.Connect();
string strQuery = "SELECT * FROM Win32_Service where Name = 'PSR Instance 7200'";
ManagementObjectSearcher moSearch = new ManagementObjectSearcher(scope, new ObjectQuery(strQuery));
ManagementObjectCollection moServices = moSearch.Get();
ManagementObject moService=null;
foreach(ManagementObject o in moServices)
moService=o;
Console.WriteLine(moServices.Count);
ManagementOperationObserver observer = new ManagementOperationObserver();
InvokeMethodCompleteHandler completionHandlerObj = new InvokeMethodCompleteHandler();
observer.Completed +=
new CompletedEventHandler(completionHandlerObj.Done);
observer.ObjectReady +=
new ObjectReadyEventHandler(completionHandlerObj.NewObject);
moService.InvokeMethod(observer,
"StopService", null);
int nCount = 0;
string strMsg=null;
while (!completionHandlerObj.IsComplete)
if (nCount > 10)
strMsg =
"manageService: Failed to ";
break;
//wait 1/2 sec.
System.Threading.
Thread.Sleep(500);
nCount++;
//if call was not successful.
if (completionHandlerObj.ReturnObject != null)
if (completionHandlerObj.ReturnObject.Properties["returnValue"].Value.ToString() == "0")
"manageService: executed successfuly";
else
Console.WriteLine(strMsg);
label1.Text = strMsg;
catch (Exception exc)
Console.WriteLine("Exception caugh" + exc.ToString());
private void Form1_Load(object sender, EventArgs e)
public class InvokeMethodCompleteHandler
private bool isComplete = false;
private ManagementBaseObject returnObject;
/// <summary>
/// Trigger Done event when InvokeMethod is complete
/// </summary>
public void Done(object sender, CompletedEventArgs e)
isComplete =
true;
public void NewObject(object sender, ObjectReadyEventArgs obj)
returnObject = obj.NewObject;
/// Get property IsComplete
public bool IsComplete
get
return isComplete;
/// Property allows accessing the result
/// object in the main function
public ManagementBaseObject ReturnObject
return returnObject;