Wednesday, September 07, 2011

Method to determine account identity of 'SharePoint 2010 Timer' (SPTimerV4) Windows Service


As a developer of solutions for the SharePoint 2010 platform, you may on occasion find the need to determine the account identity of the SharePoint 2010 Timer Windows Service (SPTimerV4). The following method will return the service's account name for you.


 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
private static string GetSPTimerJobAccountName()
{
   string retval = null;
   ServiceController[] controllers = ServiceController.GetServices();
   var cont = controllers.Where(c => c.ServiceName == "SPTimerV4");
   ServiceController svc = cont.FirstOrDefault();
   if (svc != null)
   {
       System.Management.SelectQuery query = new System.Management.SelectQuery(string.Format("select name, startname from Win32_Service where name = '{0}'", svc.ServiceName));
       using (System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(query))
       {
           foreach (System.Management.ManagementObject service in searcher.Get())
           {
               retval = service["startname"] as string;
           }
       }
   }

   return retval;
}