Monday, June 18, 2012

Getting service account of windows service from C#.Net

Again another scenario from the tool which I had to work couple of weeks back. One of installers in the release pack had a windows service installer and that windows service had to be in a particular windows service account other than NetworkService. This obviously came to the tool’s requirement basket.
When we think about the windows service management the first class which will come into mind is the ServiceController. This can be easily initialized using its constructor by passing the service name and we can play around it. But unfortunately this don’t have details about the service account on which the windows service is running . (You can get the service name easily, if you go to the log on tab in service properties). So what to do? Yes our famous WMI apis are there to help.Simply get the object of our service and get the “StartName” property.
private bool CheckWindoesServiceAccount(string serviceName,string serviceAccountName)
{
    //ServiceController sc = new ServiceController("SSBExternalActivator");
    ManagementObjectSearcher theSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_Service where Name='" + serviceName + "'");
    ManagementObjectCollection CollectionOfResults = theSearcher.Get();
    foreach (ManagementObject CurrentObject in CollectionOfResults)
    {
        Console.WriteLine(CurrentObject.Properties["StartName"].Name + " : " + CurrentObject.Properties["StartName"].Value);
        if (!CurrentObject.Properties["StartName"].Value.ToString().Contains(serviceAccountName)) return false;
        return true;
    }
    return false;
}






Happy coding.

No comments: