Is there a way to start or stop a service from powershell and block until the service starts?

I have to reset a sequence of services on a group of servers in a certain order. sc.exe is asynchronous, it will return when the service is in the START_PENDING or STOP_PENDING state. Start-Service/Stop-Service will wait for the service to start or stop, but it only works on the local machine, and I don't have remoting enabled in my environment.

Is there an alternative exe or CmdLet to do this? Looks like I'm going to have to use the .NET API.

3 Answers

Actually, it is possible to use both the Start-Service and Stop-Service PowerShell commands on a remote machine (discussion on this here). I have tested this and confirmed that it works:

Start-Service -inputobject $(get-service -ComputerName SERVER_NAME -Name SERVICE_NAME)

Also, you could try wmic to stop the service. It does appear to wait for the service to stop before continuing, although I have not thoroughly tested this.

wmic /node:"SERVER_NAME" service where name="SERVICE_NAME" call stopservice

The PowerShell cmdlets Stop-Service and Start-Service will wait until the services are fully stopped and started respectively.

You can use the -Force switch for Stop-Service to make it also stop services that depend on the service you are trying to stop.

Also if you want to get rid of the Warning message saying the cmdlet is waiting for the service to finish stopping/starting you can add the switch -WarningAction SilentlyContinue.

2

They don't have any arguments that allows you to do it synchronously.

You could instead create a while loop that checks whether the service has been started.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like