I have a few different services installed on the same machine. I'm writing a PowerShell 2 script to start and stop them.
For some of the services, I can use Start-Service -displayname "the service"
to successfully start it. On others, using the Start-Service
cmdlet causes and error along the lines of "Cannot start service ... on computer '.'".
In the cases that I get an error using the Start-Service
cmdlet, sc start "the service"
always succeeds.
Vice versa is also true (although sc start
doesn't return any errors--it just doesn't start the service at all.)
Is there any difference between these commands? Is there an alternative command I should be using? Finally, can I 'catch' any errors from the cmdlet and just include both commands to cover all the bases?
This problem is repeatable for me, even if I uninstall and reinstall the service.
Thanks!
I'm not sure the differences between sc start
and start-service
, but you can use wmi to do what you want.
To start the service:
(get-wmiobject win32_service -filter "name='the service'").startService()
To stop the service:
(get-wmiobject win32_service -filter "name='the service'").stopService()
To check the status of a service, you can use:
get-wmiobject win32_service -filter "name='the service'"
It will show you the state and also the start mode. If you want to automate this, you can use the following.
To stop the service:
if ((get-wmiobject win32_service -filter "name='the service'").state -eq "Running") {
(get-wmiobject win32_service -filter "name='the service'").stopService()
} # Stops the service if it is running
To start the service:
if ((get-wmiobject win32_service -filter "name='the service'").state -eq "Stopped") {
(get-wmiobject win32_service -filter "name='the service'").startService()
} # starts the service if it is stopped
I'm sure you can modify those to suit your needs.
The reason I like to use wmi is the ability to specify -computername
and -credentials
. It makes it so you can access a remote system and authenticate to it if you have non-domain systems. Hope that helped. Have a great day!