Tuesday, April 01, 2014

Remotely Set State and StartMode of a Service using PowerShell

Well as the name suggests this is a very simple and straightforward post.
Most of the PowerShell Geeks out there already know that we can do it in various ways:
  1. Using Set-Service
  2. Using PSRemoting
  3. Using WMI (Win32_Service)
In our environment at office we don't have PSRemoting yet enabled, but it's okey we can come around that. In addition would like it to be PowerShell v2 compatible you never know who asks you for this Script running on v2.

We can use Set-Service which has -ComputerName parameter, in case you haven't checked. But it fails to start/ stop a remote service if there are dependent services.

C:\> gsv -Name bits -ComputerName DexterClient1

Status   Name               DisplayName
------   ----               -----------
Running  bits               Background Intelligent Transfer Ser...

C:\> Set-Service -Name BITS -Status Stopped -ComputerName DexterClient1 -Verbose
VERBOSE: Performing the operation "Set-Service" on target "Background Intelligent Transfer Service (BITS)".
Set-Service : Cannot stop service 'Background Intelligent Transfer Service (BITS)' because it has dependent services.
At line:1 char:1
+ Set-Service -Name BITS -Status Stopped -ComputerName DexterClient1 -Verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.ServiceProcess.ServiceController:ServiceController) [Set-Servi
   ce], ServiceCommandException
    + FullyQualifiedErrorId : ServiceHasDependentServicesNoForce,Microsoft.PowerShell.Commands.SetServiceCommand

So it goes out of the window as there is no way to force it too (-Force switch missing)

So using WMI is a better option here.

This Script was inspired by :
  1. Set-ServiceStartMode Script by Jason Morgan here 
  2. Article by Sriram Pamarthi here 
I tweaked the Script by Jason Morgan to start/ stop the Service in addition to setting up the desired start mode and did use the pointers in Sriram's blog to get interpret the WMI Return codes properly when invoking the ChangeStartMode() and StartService() or StopService() method on the instance of Win32_Service WMI Class Object. He was kind enough to give a second opinion too. Thanks :)

The Script logs any offline machines or any Exceptions thrown and will display any warnings if it's not able to set State or StartMode. we can use re-direction probably to capture the Errors if any though or modify the Script to fit one's need.

I have uploaded the Script on Technet and POSHCode too:
Give it a shot and let me know how I can improve this further. Below is the Gist: