Changing an installed Windows service's log on account.

by Scosby Wednesday, August 26, 2009

Often, you will install a Windows service as part of your deployment. Usually, the service account (log on account) is well known (NT Authority account such as Local System, Network Service, ect) and you will install the service to run as this account, or some other specific account known at installation time. However, the need can arise to change this account as part of your application's configuration. You can accomplish this task by using the sc.exe command line utility.

sc.exe config <serviceName> obj= <domain\username> password= <password>

For example, suppose we have a service running on the local machine named "MyService" and we wish to change its log on account from local system to "acme\serviceAccount". The syntax is quite simple:

sc.exe config MyService obj= "acme\serviceAccount" password= P@ssw0rd

Now let's assume you wish to change the same service's log on account back to local system:

sc.exe config MyService obj= localsystem 

Here is a C# code snippet.

private void ChangeServiceAccount(String serviceName, String user, String password)
{
     System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo("sc.exe");

     startInfo.Arguments = String.Format("config {0} obj= {1} password= {2}", serviceName, user, password);

     startInfo.RedirectStandardOutput = true;

     startInfo.UseShellExecute = false;

     using (System.Diagnostics.Process p = new System.Diagnostics.Process())
     {
          p.StartInfo = startInfo;

          if (p.Start())
          {
               p.WaitForExit();
          }

          System.Diagnostics.Trace.WriteLine(p.StandardOutput.ReadToEnd());

          //Alternatively, you could display this in a message box
          //   MessageBox.Show(p.StandardOutput.ReadToEnd());
     }

Tags: ,

IT | Programming

blog comments powered by Disqus