Using Powershell to restart Services

As Administrators one of the most frequent things we do is restart Services . I have created a script to do just that . So the next time it will be a piece of cake . I have done this with vbscript and regular batch files but that is no fun anymore . Plus we are living in a .net world and I’m a .net person ummm hmm 🙂 So lets get to it .

In this example we will be restarting two services  . The SMS client service and the WMI service .

First we start off with this line of code :

[void] ([Reflection.Assembly]::LoadWithPartialName("System.ServiceProcess"))

What this does is tells powershell to go out and load the System.ServiceProcess namespace from our assembly dir in %winnt%. So we can use it in our code .Its basically like the using statement in C#

Now if you have a ton of servers you want to run this against you probably want to read them from a text file . That is what I normally do . So the next line we will be reading a text file that contains a bunch of servers and storing it in a variable .

$serverlist = Get-Content “.\serverlist.txt”

Simple huh ? Our variable $serverlist basically becomes an array . So now we can step thru the array like this :

foreach ($server in $serverlist) {

Our next step is to connect to our first server in the serverlist . We do that with the .net class ServiceController like this and create our smsservice variable which holds the connection .

$smsservice = [System.ServiceProcess.ServiceController]::GetServices("$server") | where-object {$_.Name -eq "CcmExec"}

There is a lot of stuff in the above line of code . I’m using the Getservices method to get all the services and piping that into the where-object to pull the service with the Name equal to CcmExec .(Notice the Serivice Name its using . Its not its displayname .)

Once we have this we can also do the same for our WMI service:

$wmiservice = [System.ServiceProcess.ServiceController]::GetServices("$server") | where-object {$_.Name -eq "WinMgmt"}

next its all gravy 🙂

Stop the smsservice:
$smsservice.Stop()
$smsservice.WaitForStatus("Stopped") # here we are waiting for the service ...very cool

Stop the WMI service
$wmiservice.Stop()
$wmiservice.WaitForStatus("Stopped")

Start the WMI Service:
$wmiservice.Start()
$wmiservice.WaitForStatus("Running") # Notice its not started .. but Running is what we are looking for

Start the SMS service
$smsservice.Start()

We stopped and started the 2 services in this order because of dependencies . You cannot stop the wmi service w/o stopping the sms service .

and finally at the end of the script remember the }… 🙂

Hope this example helps you . You can also put error trapping in place to help with error messages .

Thanks !
Chris

Advertisements