Windows – Execute Windows SC command as another user

command-line-interfacewindowswindows-service

I would like to execute the SC command against a network target as a different user. I need to be able to specify username and password on the commandline as well, as this is for scripting purposes. However, I see no options on SC for executing a command as another user. I see the 'obj' option which accepts a username, but that appears to be for setting the user account under which the service itself should run under.

If there is no way to change the user-context of the execution, is there another command that will allow me to create/start/stop a windows service in a scriptable manner (calling from TeamCity)

Best Answer

Use the "RunAs" commandline tool, it lets you supply an explicit credential set, and supports both "Domain\Username" and UPN formatting, allowing you to authenticate as another user and the run your command:

   Runas /user:Domain\user "sc \\remoteServer stop serviceKeyName"

Alternative:

Set up a scheduled task with a specific logon account