Tuesday, August 18, 2009

Check the state of a Windows service

This is yet another example of the use of CLR Interop from within Dynamics Ax. This time, we're going to retrieve the current state of a Windows service (Spooler, Telnet, ...) on any given Windows machine.
I'm using the ServiceController class from the .NET framework for this. For this example to work, make sure you have added a reference in the AOT to the System.ServiceProcess assembly.

static boolean GetServiceState(str _servicename,str _machinename)
{ System.ServiceProcess.ServiceController ServiceController;
System.ServiceProcess.ServiceControllerStatus ServiceStatus;
str myStatus;

InteropPermission permission = new InteropPermission(InteropKind::ClrInterop);
;

if(!_servicename !_machinename)
return false;

try
{
permission.assert();

ServiceController= new System.ServiceProcess.ServiceController(_servicename,_machinename);
ServiceStatus=ServiceController.get_Status();
myStatus=ServiceStatus.ToString();

if(myStatus=='Running')
return true;
} catch
{

}

return false;
}

Make sure you have appropriate rights for executing this code.

This code can be modified to start and stop services as well.

No comments:

Post a Comment