Powershell script monitors particular service , tries to restart it and send email if it fails

This is a simple script which monitores w32time service. It can monitor avery service but i choose n that particular cause w32time. What is the genral idea:

1.We get an object service in variable $st. $comp is tha variable takes the hostname of the current computer.

2. If the service isn’t starter when the script runs it tries to start it three times implemented with help of a loop.

while (($st.Status -eq “Stopped”) -and ($i -lt 3)). You can get various methods and Properties from the object in variable $st with $st | get-member. One Property is the Status of the service $st.Status.

The Retries of the script is equalt to 3. $i -lt 3. It can be more then three. If for example $i -lt 8 the script will try 8 times to start the service before it fails.(if the service fails to start 8 times).

At last if the service is still in stopped state the script sends an email to notifyyou.

$st=Get-Service w32time
$i=0
$comp=gc env:computername
while (($st.Status -eq “Stopped”) -and ($i -lt 3))
{
Start-Service w32time
$st=Get-Service w32time
$i+=1

}

if($st.Status -eq “Stopped”)
{
$sfrom=”from@domain.com
$sto=”to@domain.com
$smtpclient=New-Object system.Net.Mail.SmtpClient
$mailmessage=New-Object system.Net.Mail.MailMessage
$smtpclient.HOST=”FQDN-SMTP-SERVER”
$mailmessage.from=$sfrom
$mailmessage.To.add($sto)
$mailmessage.Subject=”Please Check the service “+$st.Name+” on machine name “+$comp+” !!!!!!!!!!!”
$mailmessage.Headers.Add(“message-id”, “<3BD50098E401463AA228377848493927-1>”)
$smtpclient.Send($mailmessage)
}

So you can save the file with ps1 extension. For Example: str-service.ps1. After that you can create bat file with the following line Powershell -command “& {C:\Scripts\str-service.ps1 }”. The bat file can be add in Shedule tasks after that with appropriate schedule.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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


%d bloggers like this: