PowerShell – Script to Monitor a Service on a Group of servers – HTML Formatted Email Output

This post explains how to monitor a given service on a group of servers. The function Get-ServiceStatusReport comprises of various cmdLets and function to monitor any given service on a list of servers.

  • Get-Service
  • HTML Ouptut
  • Email Address validation

You can customize it as per your requirement.

The Function Get-ServiceStatusReport contains five parameters

  1. computerList – List of Servers
  2. ServiceName – Name of Service
  3. SMTPMail – SMTP mail address
  4. FromID – Valid Email ID
  5. ToID – Valid Email ID

First you create the function using the below code and call the function. which is shown below

Example :-

Get-ServiceStatusReport -ComputerList c:\computer.txt -ServiceName SQL -SMTPMail mail01.pa.com -To pjayaram@ap.com -From pjayaram@ap.com

Image

Script – You can also download this script below

*******************************************************************************

Function Get-ServiceStatusReport
{
param(
[String]$ServiceName,[String]$ComputerList,[String]$To,[String]$From,[string]$SMTPMail
)
$script:list = $ComputerList
$ServiceFileName= “c:\ServiceFileName.htm”
New-Item -ItemType file $ServiceFilename -Force

# Function to write the HTML Header to the file
Function writeHtmlHeader
{
param($fileName)
$date = ( get-date ).ToString(‘yyyy/MM/dd’)
Add-Content $fileName “<html>”
Add-Content $fileName “<head>”
Add-Content $fileName “<meta http-equiv=’Content-Type’ content=’text/html; charset=iso-8859-1′>”
Add-Content $fileName ‘<title>Service Status Report </title>’
add-content $fileName ‘<STYLE TYPE=”text/css”>’
add-content $fileName “<!–”
add-content $fileName “td {“
add-content $fileName “font-family: Tahoma;”
add-content $fileName “font-size: 11px;”
add-content $fileName “border-top: 1px solid #999999;”
add-content $fileName “border-right: 1px solid #999999;”
add-content $fileName “border-bottom: 1px solid #999999;”
add-content $fileName “border-left: 1px solid #999999;”
add-content $fileName “padding-top: 0px;”
add-content $fileName “padding-right: 0px;”
add-content $fileName “padding-bottom: 0px;”
add-content $fileName “padding-left: 0px;”
add-content $fileName “}”
add-content $fileName “body {“
add-content $fileName “margin-left: 5px;”
add-content $fileName “margin-top: 5px;”
add-content $fileName “margin-right: 0px;”
add-content $fileName “margin-bottom: 10px;”
add-content $fileName “”
add-content $fileName “table {“
add-content $fileName “border: thin solid #000000;”
add-content $fileName “}”
add-content $fileName “–>”
add-content $fileName “</style>”
Add-Content $fileName “</head>”
Add-Content $fileName “<body>”

add-content $fileName “<table width=’100%’>”
add-content $fileName “<tr bgcolor=’#CCCCCC’>”
add-content $fileName “<td colspan=’4′ height=’25′ align=’center’>”
add-content $fileName “<font face=’tahoma’ color=’#003399′ size=’4′><strong>Service Stauts Report – $date</strong></font>”
add-content $fileName “</td>”
add-content $fileName “</tr>”
add-content $fileName “</table>”

}

# Function to write the HTML Header to the file
Function writeTableHeader
{
param($fileName)

Add-Content $fileName “<tr bgcolor=#CCCCCC>”
Add-Content $fileName “<td width=’10%’ align=’center’>ServerName</td>”
Add-Content $fileName “<td width=’50%’ align=’center’>Service Name</td>”
Add-Content $fileName “<td width=’10%’ align=’center’>status</td>”
Add-Content $fileName “</tr>”
}

Function writeHtmlFooter
{
param($fileName)

Add-Content $fileName “</body>”
Add-Content $fileName “</html>”
}

Function writeDiskInfo
{
param($filename,$Servername,$name,$Status)
if( $status -eq “Stopped”)
{
Add-Content $fileName “<tr>”
Add-Content $fileName “<td bgcolor=’#FF0000′ align=left ><b>$servername</td>”
Add-Content $fileName “<td bgcolor=’#FF0000′ align=left ><b>$name</td>”
Add-Content $fileName “<td bgcolor=’#FF0000′ align=left ><b>$Status</td>”
Add-Content $fileName “</tr>”
}
else
{
Add-Content $fileName “<tr>”
Add-Content $fileName “<td >$servername</td>”
Add-Content $fileName “<td >$name</td>”
Add-Content $fileName “<td >$Status</td>”
Add-Content $fileName “</tr>”
}

}

writeHtmlHeader $ServiceFileName
Add-Content $ServiceFileName “<table width=’100%’><tbody>”
Add-Content $ServiceFileName “<tr bgcolor=’#CCCCCC’>”
Add-Content $ServiceFileName “<td width=’100%’ align=’center’ colSpan=3><font face=’tahoma’ color=’#003399′ size=’2′><strong> Service Details</strong></font></td>”
Add-Content $ServiceFileName “</tr>”

writeTableHeader $ServiceFileName

#Change value of the following parameter as needed

Foreach($ServerName in (Get-Content $script:list))
{
$service = Get-Service -ComputerName $servername| where { $_.displayname -like “*$ServiceName*”}|select MachineName,Name,status

if ($Service -ne $NULL)
{
foreach ($item in $service)
{
Write-Host $item.MachineName $item.name $item.Status
writeDiskInfo $ServiceFileName $item.MachineName $item.name $item.Status
}
}

}

Add-Content $ServiceFileName “</table>”

writeHtmlFooter $ServiceFileName

function Validate-IsEmail ([string]$Email)
{

return $Email -match “^(?(“”)(“”.+?””@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$”
}

Function sendEmail
{
param($from,$to,$subject,$smtphost,$htmlFileName)
[string]$receipients=”$to”
$body = Get-Content $htmlFileName
$body = New-Object System.Net.Mail.MailMessage $from, $receipients, $subject, $body
$body.isBodyhtml = $true
$smtpServer = $MailServer
$smtp = new-object Net.Mail.SmtpClient($smtphost)
$validfrom= Validate-IsEmail $from
if($validfrom -eq $TRUE)
{
$validTo= Validate-IsEmail $to
if($validTo -eq $TRUE)
{
$smtp.Send($body)
write-output “Email Sent!!”

}
}
else
{
write-output “Invalid entries, Try again!!”
}
}

$date = ( get-date ).ToString(‘yyyy/MM/dd’)

sendEmail -from $From -to $to -subject “Service Status – $Date” -smtphost $SMTPMail -htmlfilename $ServiceFilename

}

********************************************************************

Output -

Image

Download the code here ServicesReport

Thanks for reading my space..

Happy Learning!!

About these ads

About Prashanth Jayaram

I’m a Database technologist having 8+ years of rich, hands-on experience on Database technologies. I am Microsoft Certified Professional and backed with a Degree in Master of Computer Application. My expertise lies in T-SQL programming, Replication and PowerShell. hobbies are playing sports and drawing.
This entry was posted in PowerShell and tagged , , . Bookmark the permalink.

24 Responses to PowerShell – Script to Monitor a Service on a Group of servers – HTML Formatted Email Output

  1. Steven Paulich says:

    What is the layout of c:\computer.txt?
    \\servername\instance
    \\servername\instance

    or
    instancename
    instancename
    ..
    or some other layout?

  2. Steve Miller says:

    You downloaded version of the code has computer.txt hardcoded. I’m just wondering if there are any other differences between the posted code and what is in the download file. Can you check this, thanks :)

  3. Patrick says:

    Very nice. Thanks for sharing.

  4. Shoaib says:

    Exactly what I was looking for.. great work.. thnx!!

  5. Sam says:

    How can I add multiple services to check?

  6. Narayanan says:

    Is powershell required for all the servers. From which server we need to run this powershell script

    Please advise

    • Narayanan,

      No. Windows PowerShell 2.0 is installed by default on newer versions of the Windows operating systems.

      You need have Powershell 2.0 from where you want to execute this script, Its not mandatory that the destination need to be configured with Powershell

      -Prashanth

  7. Narayanan says:

    One more question,..is this will check daily and there is no end date.

    Regards
    Narayanan.

  8. Amri says:

    Can you modify the script to send email if there are stopped services only?

  9. hari says:

    Hi Prashanth,

    when I am running it is running as infinite loop. Is there any fix for this. Please help in this regard

    • Hi Hari,

      Can you check the input file?

      Make sure that it don’t have any space and use backspace to keep the cursor to the last line of the input file.

      Let me know your test results.

      • hari says:

        Hi Prashanth,

        Thanks for reply. Still same problem, It continuously updating htm file.

  10. hari says:

    Hi Prashanth,

    I want to get only sql server services only. Is there any way we can do it

  11. Pushparaj says:

    HI , How to use this script daily using scheduled task, How to call the function in scheduled task, Please help

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