2

I have an existing Windows service on a remote machine.

Here is what I need to do:

  1. Stop that service.
  2. Delete that service.
  3. Copy my build artifacts to the specified directory on that remote machine.
  4. Recreate that Windows service.
  5. Start the Windows service.

My problem:

  • My build agents can neither stop nor delete the existing Windows service.
  • I keep getting the following error:

    [SC] OpenSCManager FAILED 5:

    Access is denied.


enter image description here

Jim G.
  • 15,141
  • 22
  • 103
  • 166
  • 2
    What steps have you taken to troubleshoot and correct the problem on your own? Does the service account that your agent is running under have appropriate permissions? – Daniel Mann Feb 12 '20 at 14:26

2 Answers2

3

@Daniel Mann asked the right question.

First of all,

sc STOP $(serviceName)

should have been a red flag.

@Daniel Mann asked:

Does the service account that your agent is running under have appropriate permissions [to do this]?

But one should also ask:

Which machine are you looking to execute this against? The build agent?

This was, in fact, my problem. When I tested this release pipeline the first time, the target machine and the build agent just happened to be the same machine.

This was an unfortunate accident, because this was not to be the case for all releases.


Solution:

This is correct:

sc \\$(serviceMachine) STOP $(serviceName)

And @Daniel Mann was correct:

  • The service account that the build agent is running under must have the appropriate permissions to do this.
Jim G.
  • 15,141
  • 22
  • 103
  • 166
  • The key thing for me here was that the service account did not have permission, this can be added using the PowerShellAccessControl module and the command Get-Service -computer MACHINENAME SERVICENAME | Add-AccessControlEntry -ServiceAccessRights Start,Stop -Principal USERNAME – ximon Jan 25 '23 at 10:26
1

There are a couple ways to achieve this, but I'm gonna describe one that I recommend using PowerShell:

  1. On your deployment tasks, add "Run PowerShell" task;
  2. Select inline script and paste the code bellow:

    Get-Service -DisplayName "YOUR_SERVICE_NAME" | Stop-Service
    
  3. Copy artifact files to destination folder (as you did);
  4. Repeat step 1 and paste the code below to re-create and start the service:

    $params = @{
      Name = "YOUR_SERVICE_NAME"
      BinaryPathName = "C:\WINDOWS\System32\svchost.exe -k netsvcs"
      DependsOn = "NetLogon"
      DisplayName = "Test Service"
      StartupType = "Manual"
      Description = "This is a test service."
    }
    New-Service @params
    

You can read more about service creation parameters at Microsoft Docs: