Start a Windows Service with Powershell

I have finally scheduled an ice fishing trip. I’m going to be taking my son out on Sunday for a little while. I have to admit that I’m a bit nervous about ice fishing. I haven’t been out too many times, so I don’t really know how to judge how safe the ice is. Additionally, we’ve had an extremely mild winter. With the exception of one week where it was far below freezing, it has been oscillating back and forth over the freezing point daily. Yesterday was relatively warm – the temperature was probably between 32 and 40 degrees throughout the day. Today is colder, with temps in the 20s. The next post should have reports from the upcoming fishing trip.
I was recently tasked with creating a powershell script to make sure a Windows Service had started correctly. One of our applications would often start but then run into a phantom error a short time later and stop. We have a Task Scheduler job that stops the service, then starts it again a short time later each night. I decided to create a script that would check the status of the service. If it is started, then quit. If it is stopped, attempt to start it and wait five minutes, then do it again. Keep repeating the process until the service starts and stays started. I also decided to add a logging component to this script, which I had never done before. I though it would be useful to be able to see how many times the script had to try to start the service each time. Here is the script:

$Logfile = 'C:\AppName\Powershell Start AppName Log.log'

Function LogWrite
   Param ([string]$logstring)
   Add-content $Logfile -value $logstring

$ServiceName = 'AppName'
$arrService = Get-Service -Name $ServiceName
LogWrite "$(Get-Date) Start AppName Service powershell script started."

while ($arrService.Status -ne 'Running')
   LogWrite "$(Get-Date) Service is currently in $($arrService.Status) status"
   Start-Service $ServiceName
   LogWrite "$(Get-Date) Attempting to start AppName service"
   Start-Sleep -seconds 300
   if ($arrService.Status -eq 'Running')
       LogWrite "$(Get-Date) Service has started successfully."
       LogWrite "$(Get-Date) Service has failed to start, preparing to retry."

This is another example of how we can use Powershell to make our lives easier.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s