Thursday, October 9, 2008

Manipulating remote services with Powershell 1.0

I know Powershell 2.0 CTP2 includes remote support for the get/set-service cmdlet, but I cannot use beta code in production and needed a way to use Powershell to accomplish the same functions we use the Resource Kit "sc.exe" tool for now (start, stop, enable/disable).

After much googling, this turned out to be insanely simple, yet hard to find.

First, get the remote service using WMI:
$Svc = Get-WmiObject -Computer $Server win32_service -filter "name='$Service'"
Second, issue the appropriate control command:
To start a service:
$Result = $Svc.StartService()
To stop a service:
$Result = $Svc.StopService()
To disable a service:
$Result = $Svc.ChangeStartMode("Disabled")
To enable a service for manual:
$Result = $Svc.ChangeStartMode("Manual")
To enable a service for auto start:
$Result = $Svc.ChangeStartMode("Auto")

Third, check if the command worked; just look for $Result.ReturnValue. It should be "0" if it succeeded.:
$Result.ReturnValue

For reference, "5" means you tried to stop an already stopped service and "10" means you tried to start and already started service.

You can also check the current state by:
$Svc.State
And the current StartMode by:
$Svc.StartMode

I would also add in a step after calling "Get-WmiObject" to verify you actually connected to a service. There is no response if the service didn't exist, but you can simply check if $Svc is null or not:
If (!($Svc)) { #perform action }

If this wasn't fully helpful for you (i.e. you want to manipulate lots of services or many machines) I found the best google search term to be "powershell win32_service" from http://google.com/microsoft

3 comments:

Philipp said...

yippiieeh! that's is what i really wanted to find. and you're right. quite easy, but hard to google :)

greetings Philipp

Cthutbx said...

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
$Result = $Svc.ChangeStartMode("Automatic")
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

DklSpec said...

"Disabled", "Manual", "Automatic" (instead of "Auto")
This worked for me on windows 2003