C#/Windows: Find which account a service is set to “Log On As”

Find which account a service is set to “Log On As”

Problem:

How to find out the user account (Local System/User etc) a service is set to run under ("Log On As")?

Unlike this similar question this code can’t run from within the service itself and the service may not be running.

The System.ServiceProcess.ServiceController class has useful methods for getting the status but not the "Log On As" user.

Solution:

This is the only way I know of, I found it looking around and tested it, it works. Make sure you use the Service Name not it’s Display Name, you will also need to add a reference to System.Management.

private static void GetLogOnAsForAService()

{

string serviceName = "myAppserverService";

SelectQuery query = new System.Management.SelectQuery(string.Format(

"select name, startname from Win32_Service where name = ‘{0}’", serviceName));

using (ManagementObjectSearcher searcher =

new System.Management.ManagementObjectSearcher(query))

{

foreach (ManagementObject service in searcher.Get())

{

Console.WriteLine(string.Format(

"Name: {0} – Logon : {1} ", service["Name"], service["startname"]));

}

}

}

References:

http://stackoverflow.com/questions/1631926/find-which-account-a-service-is-set-to-log-on-as

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s