How Can I Tell Which Account a Service is Running Under?

Hey, Scripting Guy! Question

We have services that run under a particular user account. Each time we change the password for that user account, we need to change the password for any services that run under that account as well. But how can we tell which account a service is running under?

— SA

SpacerHey, Scripting Guy! AnswerScript Center

Hey, SA. By and large WMI is a pretty transparent technology. To manage services, you use a class named Win32_Service. To manage processes, you use a class named Win32_Process. Not exactly rocket science, right?


Of course, every now and then WMI throws you a curve, and the service account name happens to be one of those instances. It’s actually easy to determine the account name under which a service runs, provided you know that this information is found using the StartName property:

strComputer = “.”
Set objWMIService = GetObject _
(“winmgmts:\\” & strComputer & “\root\cimv2”)
Set colServices = objWMIService.ExecQuery _
(“Select * From Win32_Service”)
For Each objService in colServices
Wscript.Echo objService.Name, objService.StartName
Next

The preceding code shows you the name and account name for each service installed on a computer. If you only want a list of services running under a specific account (e.g., KenMyer), then use code similar to this:

strComputer = “.”
Set objWMIService = GetObject _
(“winmgmts:\\” & strComputer & “\root\cimv2”)
Set colServices = objWMIService.ExecQuery _
(“Select * From Win32_Service Where StartName = ‘KenMyer'”)
For Each objService in colServices
Wscript.Echo objService.Name
Next

And then how do you change the password using a script? Why, by using a script like this one:

strComputer = “.”
Set objWMIService = GetObject _
(“winmgmts:\\” & strComputer & “\root\cimv2”)
Set colServices = objWMIService.ExecQuery _
(“Select * From Win32_Service Where StartName = ‘KenMyer'”)
For Each objService in colServices
errReturn = objService.Change( , , , , , , , “fgT54ghde*&”)
Next

Note that when using the Change method, the password is the eighth parameter passed. That means you must preface the new password (“fgT54ghde*&”) with seven commas. A bit odd, but it works.