Mike Pateras
Mike Pateras

Reputation: 15015

How can I remotely start/stop a service using MSBuild?

I'd like to remotely start or stop a windows service on another machine using MSBuild. To accomplish this, I wrote this script:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="C:\Program Files (x86)\MSBuild\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets"/>
  <Target Name="MyTarget">
    <ServiceController MachineName="Box2" ServiceName="MyService" Action="Stop" />
  </Target>
</Project>

When I run that on a machine that can see Box2, I get this:

Project "C:\Scripts\Test.xml" on node 1 (default targets).

C:\Scripts\Test.xml(4,5): error : Couldn't find the 'MyService' service on 'Box2' Done Building Project

"C:\Scripts\Test.xml" (default targets) -- FAILED.

I know that I have the service name correct (I copied and pasted it from the actual service list), and I'm pretty sure that it can see Box2 because if I change it to a machine name that doesn't exist (e.g. Box2asdf), it takes about 10 seconds to come back (with the exact same error, mind you), as opposed to the nearly immediate response that I get when I provide the correct machine name.

How might I debug this issue?

Upvotes: 4

Views: 3572

Answers (3)

Sergio Rykov
Sergio Rykov

Reputation: 4286

ServiceController Target internally uses ServiceController Class. But it doesn't return the reason why it couldn't find the service. If you are shure that both computer and service names are correct, the next thing I can suggest to analyze is access violation problems.

And @jsobo's answer can be very useful to diagnose the actual reason because it can show native errors without .Net exception wrappers around them:

sc.exe \Box2 stop MyService

Upvotes: 0

James Woolfenden
James Woolfenden

Reputation: 6661

The community tasks should work. Just use Sc query to check that the service does work. as for using msbuild its still using msbuild if you wrap sc in an exec? At least you dont have a dependency on a third party dll in your build process.

Upvotes: 0

John Sobolewski
John Sobolewski

Reputation: 4572

You might try this instead...

You can use the command line program sc and execute that...

ie

SC \ServerName stop ServiceName

http://support.microsoft.com/kb/166819

For more information on how to execute a command from msbuild check this out.. execute a command with parameters using msbuild

Upvotes: 2

Related Questions