How do I grant permissions to remotely start/stop a service using Powershell?

We have a PowerShell script that restarts a service on another computer. When we use PowerShell's built-in service control cmdlets, like so:

$svc = Get-Service -Name MyService -ComputerName myservicehostname
Stop-Service -InputObject $svc
Start-Service -InputObject $svc

We get this error back:

Stop-Service : Cannot open MyService service on computer 'myservicehostname'.

However, when we use sc.exe, like so:

C:\Windows\System32\sc \\myservicehostname stop MyService
C:\Windows\System32\sc \\myservicehostname start MyService

the start and stop succeed.

The user doing the restarting is not an administrator. We use subinacl to grant the user permissions to start/stop and query the service:

subinacl.exe /service MyService /GRANT=MyServiceControlUser=STO

How come PowerShell can't stop my service but sc.exe can?


Solution 1:

It turns out I wasn't giving enough permissions with subinacl. The possible access values for the grant action are:

    F : Full Control  
    R : Generic Read  
    W : Generic Write  
    X : Generic eXecute  
  or any following values  
    L : Read controL  
    Q : Query Service Configuration  
    S : Query Service Status  
    E : Enumerate Dependent Services  
    C : Service Change Configuration  
    T : Start Service  
    O : Stop Service  
    P : Pause/Continue Service  
    I : Interrogate Service  
    U : Service User-Defined Control Commands  

I was using S (Query Service Status), T (Start Service), and O (Stop Service). I also needed E (Enumerate Dependent Services). It appears that the PowerShell cmdlets need to look at dependent services when starting/stopping.

Here's my updated subinacl command:

subinacl.exe /service MyService /GRANT=MyServiceControlUser=STOE

If you don't want to download/use subinacl.exe, you can use PowerShell via the Carbon module's Grant-ServiceControlPermission or Grant-ServicePermission functions. (DISCLAIMER: I am the owner/maintainer of the Carbon project.)