PRTG Daily Email Powershell Script

PRTG-LogoSo I don’t write much powershell but recently I needed a way to send daily emails out of PRTG. Thanks Paessler which has kept it simple with their PRTG monitoring system as the hardest part of this script was getting the data in HTML. (Remember I don’t write much powershell. 😉 ) If you have not used PRTG before check it out if you need some alerting in your environment. Personally this is one of my favorite systems for just monitoring because a lot of other monitoring systems include everything but the kitchen sink and reality we just need to know what’s up and what’s down.

This script grabs an XML file that PRTG builds and saves it as “table.xml” I have the script check if there are any sensors in trouble if not send an email. If PRTG is reporting a sensor or sensors that are in trouble this scripts builds an HTML document with a table and list the sensors in trouble highlighting the status column with the appropriate color and sends an email. Thanks goes to Martin Pugh who has provided the set-cellcolor function. 🙂

# Load up the function "Set-CellColor" thanks to Martin Pugh 🙂
Function Set-CellColor
{   <#
        Function that allows you to set individual cell colors in an HTML table
        To be used inconjunction with ConvertTo-HTML this simple function allows you
        to set particular colors for cells in an HTML table.  You provide the criteria
        the script uses to make the determination if a cell should be a particular 
        color (property -gt 5, property -like "*Apple*", etc).
        You can add the function to your scripts, dot source it to load into your current
        PowerShell session or add it to your $Profile so it is always available.
        To dot source:
    .PARAMETER Property
        Property, or column that you will be keying on.  
    .PARAMETER Color
        Name or 6-digit hex value of the color you want the cell to be
    .PARAMETER InputObject
        HTML you want the script to process.  This can be entered directly into the
        parameter or piped to the function.
    .PARAMETER Filter
        Specifies a query to determine if a cell should have its color changed.  $true
        results will make the color change while $false result will return nothing.
        <Property Name> <Operator> <Value>
        <Property Name>::= the same as $Property.  This must match exactly
        <Operator>::= "-eq" | "-le" | "-ge" | "-ne" | "-lt" | "-gt"| "-approx" | "-like" | "-notlike" 
            <JoinOperator> ::= "-and" | "-or"
            <NotOperator> ::= "-not"
        The script first attempts to convert the cell to a number, and if it fails it will
        cast it as a string.  So 40 will be a number and you can use -lt, -gt, etc.  But 40%
        would be cast as a string so you could only use -eq, -ne, -like, etc.  
        Instructs the script to change the entire row to the specified color instead of the individual cell.
        HTML with table
        get-process | convertto-html | set-cellcolor -Propety cpu -Color red -Filter "cpu -gt 1000" | out-file c:\test\get-process.html

        Assuming Set-CellColor has been dot sourced, run Get-Process and convert to HTML.  
        Then change the CPU cell to red only if the CPU field is greater than 1000.
        get-process | convertto-html | set-cellcolor cpu red -filter "cpu -gt 1000 -and cpu -lt 2000" | out-file c:\test\get-process.html
        Same as Example 1, but now we will only turn a cell red if CPU is greater than 100 
        but less than 2000.
        $HTML = $Data | sort server | ConvertTo-html -head $header | Set-CellColor cookedvalue red -Filter "cookedvalue -gt 1"
        PS C:\> $HTML = $HTML | Set-CellColor Server green -Filter "server -eq 'dc2'"
        PS C:\> $HTML | Set-CellColor Path Yellow -Filter "Path -like ""*memory*""" | Out-File c:\Test\colortest.html
        Takes a collection of objects in $Data, sorts on the property Server and converts to HTML.  From there 
        we set the "CookedValue" property to red if it's greater then 1.  We then send the HTML through Set-CellColor
        again, this time setting the Server cell to green if it's "dc2".  One more time through Set-CellColor
        turns the Path cell to Yellow if it contains the word "memory" in it.
        $HTML = $Data | sort server | ConvertTo-html -head $header | Set-CellColor cookedvalue red -Filter "cookedvalue -gt 1" -Row
        Now, if the cookedvalue property is greater than 1 the function will highlight the entire row red.
        Author:             Martin Pugh
        Twitter:            @thesurlyadm1n
        Spiceworks:         Martin9700
            1.5             Added ability to set row color with -Row switch instead of the individual cell
            1.03            Added error message in case the $Property field cannot be found in the table header
            1.02            Added some additional text to help.  Added some error trapping around $Filter
            1.01            Added verbose output
            1.0             Initial Release

    Param (
    Begin {
        Write-Verbose "$(Get-Date): Function Set-CellColor begins"
        If ($Filter)
        {   If ($Filter.ToUpper().IndexOf($Property.ToUpper()) -ge 0)
            {   $Filter = $Filter.ToUpper().Replace($Property.ToUpper(),"`$Value")
                Try {
                    [scriptblock]$Filter = [scriptblock]::Create($Filter)
                Catch {
                    Write-Warning "$(Get-Date): ""$Filter"" caused an error, stopping script!"
                    Write-Warning $Error[0]
            {   Write-Warning "Could not locate $Property in the Filter, which is required.  Filter: $Filter"
    Process {
        ForEach ($Line in $InputObject)
        {   If ($Line.IndexOf("<tr><th") -ge 0)
            {   Write-Verbose "$(Get-Date): Processing headers..."
                $Search = $Line | Select-String -Pattern '<th ?[a-z\-:;"=]*>(.*?)<\/th>' -AllMatches
                $Index = 0
                ForEach ($Match in $Search.Matches)
                {   If ($Match.Groups[1].Value -eq $Property)
                    {   Break
                    $Index ++
                If ($Index -eq $Search.Matches.Count)
                {   Write-Warning "$(Get-Date): Unable to locate property: $Property in table header"
                Write-Verbose "$(Get-Date): $Property column found at index: $Index"
            If ($Line -match "<tr( style=""background-color:.+?"")?><td")
            {   $Search = $Line | Select-String -Pattern '<td ?[a-z\-:;"=]*>(.*?)<\/td>' -AllMatches
                $Value = $Search.Matches[$Index].Groups[1].Value -as [double]
                If (-not $Value)
                {   $Value = $Search.Matches[$Index].Groups[1].Value
                If (Invoke-Command $Filter)
                {   If ($Row)
                    {   Write-Verbose "$(Get-Date): Criteria met!  Changing row to $Color..."
                        If ($Line -match "<tr style=""background-color:(.+?)"">")
                        {   $Line = $Line -replace "<tr style=""background-color:$($Matches[1])","<tr style=""background-color:$Color"
                        {   $Line = $Line.Replace("<tr>","<tr style=""background-color:$Color"">")
                    {   Write-Verbose "$(Get-Date): Criteria met!  Changing cell to $Color..."
                        $Line = $Line.Replace($Search.Matches[$Index].Value,"<td style=""background-color:$Color"">$Value</td>")
            Write-Output $Line
    End {
        Write-Verbose "$(Get-Date): Function Set-CellColor completed"
# Load up the variables, feel free to edit below like what is your email server?
$smtp = ""
# Who is this email going to?
$to = "Mr. Joe <>"
# Carbon Copy anyone?
$cc = "Mr. Admin <>"
$from = "PRTG Network Monitor <>"
$subject = "PRTG Checks"
$time = Get-Date
# Get a table ready in HTML just in case we have alerts in PRTG.
$a = "<style>"
$a = $a + "BODY{background-color:White;}"
$a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
$a = $a + "TH{Font-family: Courier; color: white; border-width: 1px;padding: 3px;border-style: solid;border-color: black;background-color:black}"
$a = $a + "TD{Font-family: Courier; border-width: 1px;padding: 3px;border-style: solid;border-color:}"
$a = $a + "</style>"
# Write out something in HTML in case we have alerts in PRTG.
$b = "<H2>PRTG Alerts</H2>"
$b = $b + "<p>Houston, we have a problem so please reference the chart below.</p>"
$b = $b + "<p>System Generated at $time.</p>"
# Write out something in HTML in case no alerts are active. 
$c = "<H2>PRTG Alerts </H2>"
$c = $c + "<p>No alerts being reported.</p>"
$c = $c + "<p>System Generated at $time.</p>"
# URL to your PRTG server you will need to reference a local user account and password that has access to PRTG. See the end of the URL. 
$url = ",downtimesince,device,sensor,lastvalue,status,message,priority&filter_status=5&filter_status=4&filter_status=10&filter_status=13&filter_status=14&sortby=priority&username=GOES_HERE&passhash=GOES_HERE"
# Where do you want to store the XML file?
$destination = "C:\PRTG-DAILY-EMAIL\table.xml"
# What colors do you like for each alert?
# You have a lot to choose from
$AckColor = "LightPink"
$AckMsg = "Down (Acknowledged) "
$DownColor = "Red"
$DownMsg = "Down "
$WarnColor = "Yellow"
$WarnMsg = "Warning "
$SimColor ="DarkSalmon"
$SimMsg = "Down  (simulated error)"
$outfile ="C:\PRTG-DAILY-EMAIL\HTML.htm"

# Let's run the powershell script

Invoke-WebRequest $url -Outfile $destination
$xml = [xml](Get-Content .\table.xml)
# If nothing is alerting in PRTG we don't need to stay around. Let's say something about it and quit out.
if ($xml.sensors.totalcount -eq 0) {
ConvertTo-Html -Body $c | Out-File $outfile
$emailbody = Get-Content $outfile | Out-String
send-MailMessage -BodyAsHtml -SmtpServer $smtp -To $to -Cc $cc -From $from -Subject $subject -body $emailbody
$HTML = $xml.sensors.item | Sort-Object -Property device | select device,downtimesince,sensor,status,message_raw |
ConvertTo-HTML -head $a -body $b 
$HTML = $HTML | Set-cellcolor status $WarnColor -Filter "status -eq '$WarnMsg'"
$HTML = $HTML | Set-cellcolor status $DownColor -Filter "status -eq'$DownMsg'"
$HTML = $HTML | Set-cellcolor status $AckColor -Filter "status -eq'$AckMsg'"
$HTML = $HTML | Set-cellcolor status $SimColor -Filter "status -eq'$SimMsg'"
$HTML | Out-File $outfile
$emailbody = Get-Content $outfile | Out-String
send-MailMessage -BodyAsHtml -SmtpServer $smtp -To $to -Cc $cc -From $from -Subject $subject -body $emailbody

So in the end you should get an email that looks something below if something is wrong. That’s all I got I hope this information is helpful feel free to edit this and use it!

PRTG Sample Alert


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