Can I check for specific HTTP Response codes with PRTG?
Best Answer
If someone needs a Powershell variant to use with an EXE/Script Advanced sensor:
<# .SYNOPSIS Query an HTTP Endpoint to Measure the Response Time and the HTTP Status Code .DESCRIPTION This script is able to query an HTTP/HTTPS Endpoint and measure the response time as well as the HTTP Status Code. The script is designed to be used with PRTG Network Monitor (https://www.paessler.com/prtg). .PARAMETER Url The Uniform Resource Locator (URL) you want to query, including the protocol (and path).: https://example.org or http://example.com:8080/myfile.htm .PARAMETER Timeout The number of seconds to wait for the HTTP query to complete (Default: 30) .EXAMPLE Running the script interactively to test it: PS> .\Get-HTTPStatusCode.ps1 -Url "https://example.org/" -Timeout 10 .EXAMPLE For running the script in PRTG, you can use PRTG's placeholders to make the setup more robust: Parameters(in the Sensor's settings): -Url "https://%host/" -Timeout 10 However, it's also possible to enter the full URL in the sensor as expected: Parameters(in the Sensor's settings): -Url "https://example.org/" -Timeout 10 .EXAMPLE If you're monitoring an endpoint with an invalid certificate (expired, self-signed, etc) you can enable the TrustAllCerts switch, like this: PS> .\Get-HTTPStatusCode.ps1 -Url "https://invalidsslserver.example.org/" -Timeout 10 -TrustAllCerts .NOTES Version: 2.2.20220317 Author: Luciano Lingnau, Paessler AG (https://www.paessler.com/) .LINK https://kb.paessler.com/en/topic/47373 #> #Requires -Version 3.0 param( [Parameter(Mandatory=$true)] [string]$Url, [int]$Timeout = "30", [switch]$TrustAllCerts = $false ) [string]$sensorMessage = '' $errorFlag = $false $results = @() #Avoid issues with weird SSL Certificates (Self-signed, expired, etc) #Should only be used when a trusted certificate is not an option if ($TrustAllCerts){ add-type @" using System.Net; using System.Security.Cryptography.X509Certificates; public class TrustAllCertsPolicy : ICertificatePolicy { public bool CheckValidationResult( ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) { return true; } } "@ [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy } try { #Stopwatch used to time the lenghtiest part of the execution (long execution times could be an issue) $exectime = [System.Diagnostics.Stopwatch]::StartNew() $a = Invoke-WebRequest -Uri $Url -TimeoutSec $Timeout -UseBasicParsing -ErrorAction SilentlyContinue #Stop Stopwatch used to time the lenghtiest part of the execution $exectime.Stop() #Parse the results in a PRTG Friendly way if ($a.StatusCode){ $results += @{ Channel = 'Status Code' Value = $a.StatusCode valuelookup = 'prtg.standardlookups.http.statuscode' } $results += @{ Channel = 'Length' Value = $a.RawContentLength } $results += @{ Channel = 'Execution Time' Value = $exectime.ElapsedMilliseconds Unit = 'TimeResponse' } } $sensorMessage = "$($url)" } catch { #If there is a valid statuscode in the response (like 3XX) we want that to be a sensor result, so this has to be handled in the try/catch if ($_.Exception.Response.StatusCode.Value__ -gt 0){ #Parse the results in a PRTG Friendly way $results += @{ Channel = 'Status Code' Value = $_.Exception.Response.StatusCode.Value__ valuelookup = 'prtg.standardlookups.http.statuscode' } $results += @{ Channel = 'Length' Value = '-1' } $results += @{ Channel = 'Execution Time' Value = $exectime.ElapsedMilliseconds Unit = 'TimeResponse' } $sensorMessage = "$($url)" }else{ #Otherwise it's an exception that doesn't have a valid result $errorFlag = $true $sensorMessage = "Exception (Line $($_.InvocationInfo.ScriptLineNumber)): $($_.Exception.Message)" } } $sensorResult = '' | Select-Object prtg if ($errorFlag) { $sensorResult.prtg = '' | Select-Object error $sensorResult.prtg.error = 1 } else { $sensorResult.prtg = '' | Select-Object result $sensorResult.prtg.result = $results } if ($sensorMessage) { $sensorResult.prtg | Add-Member -MemberType NoteProperty -Name 'text' -Value $null $sensorResult.prtg.text = $sensorMessage } $sensorResult | ConvertTo-Json -Depth 5 | Write-Output
In order to pass the url from the sensor's settings, enter it like this in the "Parameters" field:
-Url "https://example.org/" -Timeout 10
Using %host in the parameters as a placeholder like this will also work:
-Url "https://%host/" -Timeout 10
And if you're encountering issues with SSL, try adding TrustAllCerts to the parameters:
-Url "https://%host/" -Timeout 10 -TrustAllCerts
The channel displaying the return code uses an already existing lookup (prtg.standardlookups.http.statuscode) to evaluate which codes are regarded as OK/Warning/Error. Feel free to create a custom lookup based on the existing one if you need.
On a side-note: There's also another lookup called "prtg.standardlookups.http.statuscodedetailed" which contains definitions for every single return code, instead of ranges as in "prtg.standardlookups.http.statuscode".
Changelog:
- 17/03/2022 - Version 2.2 completely changes the code to a more modular approach which is easier to maintain. Functionally almost identic to 1.0
- 09/03/2022 - Version 1.0 includes some bigger changes and is not backwards compatible (the parameters changed slightly). What's new: Invalid certificates are now only accepted when the switch-parameter TrustAllCerts is set. Otherwise you will see an SSL Error. Also fixed a small issue with the units from the ExecTime channel. Added better documentation and examples in the code itself
- 01/09/2021 - Switched from Write-Host to Write-Output to conform with new "PowerShell Security Enhancement" (As of PRTG 21.2.68)
- 25/06/2018 - Modified the try/catch to properly read the status code when it is part of an exception. When this happens, the Length is reported as -1.
- 10/04/2018 - Added code to ignore SSL Certificate errors.
- 28/07/2017 - Included a parameter for timeout. Default = 10 (seconds).
Created on Jan 4, 2017 7:53:50 AM by
Luciano Lingnau [Paessler]
Last change on Mar 17, 2022 4:07:28 PM by
Luciano Lingnau [Paessler]
25 Replies
There is no native Sensor within PRTG which can do this but you may use the following script in addition to a EXE/Script Sensor:
sUrl = "http://www.google.com" sStatusToCheck = 200 If Wscript.Arguments.Count = 1 then sUrl = Wscript.Arguments(0) End If If Wscript.Arguments.Count = 2 then sUrl = Wscript.Arguments(0) sStatusToCheck = Wscript.Arguments(1) End If Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.3.0") oXMLHTTP.Open "GET", sUrl, False, " "," " oXMLHTTP.Send WScript.Echo oXMLHTTP.Status & ":" & oXMLHTTP.StatusText If oXMLHTTP.Status = sStatusToCheck then WScript.Quit("0") Else WScript.Quit("2") End If
The script can be called with parameters, where the first parameter has to be the URL and the second parameter has to be the Status Code to check for (e.g. 200,401,...).
Kudos for the script go to PRTG User Colby.
Nice script! Thnx! I extended it a bit, by disabling redirects, adding post values and extending error handling:
'************************************************ '** Init '************************************************ Option Explicit Dim oXMLHTTP Dim url, postParameter Const WinHttpRequestOption_EnableRedirects = 6 '************************************************ '** Configuration parameters '************************************************ url = "http://www.google.com" postParameter = "" '************************************************ '** Main '************************************************ If Wscript.Arguments.Count = 1 then url = Wscript.Arguments(0) ElseIf Wscript.Arguments.Count = 2 then url = Wscript.Arguments(0) postParameter = Wscript.Arguments(1) End If Set oXMLHTTP = CreateObject("WinHttp.WinHttpRequest.5.1") oXMLHTTP.Option(WinHttpRequestOption_EnableRedirects) = false oXMLHTTP.Open "POST", url, False oXMLHTTP.Send postParameter '************************************************ '** Return value '************************************************ If Err.Number = 0 Then WScript.Echo oXMLHTTP.Status & ":" & oXMLHTTP.StatusText WScript.Quit(0) Else WScript.Quit(2) End If
Created on Mar 27, 2013 10:55:26 AM by
Peter Pronk
(0)
Last change on Mar 27, 2013 11:52:18 AM by
Konstantin Wolff [Paessler Support]
Here is an updated version, I believe there was a bug with Konstantin's version: when sStatusToCheck
is given as argument, it is cast as string, not int, so the status part of the script should be:
[...]
If oXMLHTTP.Status = CInt(sStatusToCheck) then
[...]
Here is a revised version (note: http only, https support should be fairly easy, or duplicate the check):
'****************************************************************************** '** Script to check a specific HTTP return code '** '** Authors: PRTG User Colby, Konstantin Wolff (Paessler Support), Thomas Blanchard - [email protected] '** Version: 0.01 '** Version Date: 2014-12-03 '** Source: '** - https://kb.paessler.com/en/topic/47373-can-i-check-for-specific-http-response-codes-with-prtg '****************************************************************************** sHost = "www.lynda.com" sStatusToCheck = 200 If Wscript.Arguments.Count = 1 then sHost = Wscript.Arguments(0) End If If Wscript.Arguments.Count = 2 then sHost = Wscript.Arguments(0) sStatusToCheck = Wscript.Arguments(1) End If sUrl = "http://" & sHost & "/" ' WScript.Echo sUrl & " " & sStatusToCheck Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.3.0") oXMLHTTP.Open "GET", sUrl, False, " "," " oXMLHTTP.Send sMsg = sHost & " returns " & oXMLHTTP.Status & " " & oXMLHTTP.StatusText & " (expecting " & sStatusToCheck & ")" If oXMLHTTP.Status = CInt(sStatusToCheck) then WScript.Echo oXMLHTTP.Status & ":OK " & sMsg WScript.Quit("0") Else WScript.Echo oXMLHTTP.Status & ":ERROR " & sMsg WScript.Quit("2") End If
Can you please post how should parameters be typed for different url and status code? I can not get it work with parameters.
Hi Ozgur,
You can also try the following PowerShell script: http://pastebin.com/KpCSbrzt
Call it with the following parameters:
-URL "www.google.de" -ResponseCode 220 -Protocol "HTTP"
Note Remember to execute a PowerShell (x86) with admin privileges and run
Set-ExecutionPolicy RemoteSigned
...in order to make the script work :)
Hello,
I am currently running the Powershell script that Stephan posted, and the script itself is running correctly (from what I can tell). PRTG, however, is not picking up on the value that the script is putting out, and I am getting "Unauthorized access" as the last message. Any thoughts?
What URL are you trying to check?
Stephan,
I modified your version of the Powershell script (see below) so that I am able to successfully get response codes in our environment. PRTG is giving me an "Unauthorized Access" error when I tell the EXE/Script Sensor to run it. Any thoughts?
param( [string]$URL, [int]$ResponseCode1 = "", [int]$ResponseCode2 = "200", [string]$DefaultDNS = "false", [string]$protocol = "https", [string]$HeaderHost = "https://mobile.processnow.com" ) # Ignore SSL errors [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true} $URL = $HeaderHost $req = [system.Net.WebRequest]::Create($URL) # Add some headers to the web request (for round robin dns and load balancers) #$req.$Host = $HeaderHost; $req.AllowAutoRedirect=$true # catch exceptions try { $res = $req.GetResponse() } catch [System.Net.WebException] { $res = $_.Exception.Response } # get the numeric response code of the request $ResponseCode1 = (($res.StatusCode) -as [int]) # and some error handling if([int]$ResponseCode1 -eq [int]$ResponseCode2){ Write-Host $ResponseCode2":Page returned HTTP code "$ResponseCode1" as expected (used "$URL")."; exit 0; } elseif([int]$ResponseCode1 -eq 200){ Write-Host $ResponseCode1":Connection error (used "$URL")."; } else{ Write-Host $ResponseCode1":Page returned "$ResponseCode1" instead of $ResponseCode2 unexpectedly (used "$URL")."; }
Created on Dec 29, 2015 7:06:19 PM by
Todd Schroeder
(0)
●1
Last change on Dec 30, 2015 8:09:31 AM by
Torsten Lindner [Paessler Support]
Can you post your sensor settings? You probably have to set "Use security context of parent device" in the sensor security context settings. Can you check that?
I have set the security settings to "Use security context of parent device." I am still getting Unauthorized Access, however I am showing that the value is 0. According to the manual, the #0 indicates that the script is running ok. Right?
Are you using a proxy server by any chance? What's the output of the script when run in PowerShell?
We do have proxies setup between the two locations.
When I run the script manually in Powershell, the output is this:
200:Page returned HTTP code 200 as expected (used https://register.processnow.com).
Is the proxy server configured via GPO? Or via IE? Can you try a different windows user in the parent device credential settings? Probably your own user account?
If someone needs a Powershell variant to use with an EXE/Script Advanced sensor:
<# .SYNOPSIS Query an HTTP Endpoint to Measure the Response Time and the HTTP Status Code .DESCRIPTION This script is able to query an HTTP/HTTPS Endpoint and measure the response time as well as the HTTP Status Code. The script is designed to be used with PRTG Network Monitor (https://www.paessler.com/prtg). .PARAMETER Url The Uniform Resource Locator (URL) you want to query, including the protocol (and path).: https://example.org or http://example.com:8080/myfile.htm .PARAMETER Timeout The number of seconds to wait for the HTTP query to complete (Default: 30) .EXAMPLE Running the script interactively to test it: PS> .\Get-HTTPStatusCode.ps1 -Url "https://example.org/" -Timeout 10 .EXAMPLE For running the script in PRTG, you can use PRTG's placeholders to make the setup more robust: Parameters(in the Sensor's settings): -Url "https://%host/" -Timeout 10 However, it's also possible to enter the full URL in the sensor as expected: Parameters(in the Sensor's settings): -Url "https://example.org/" -Timeout 10 .EXAMPLE If you're monitoring an endpoint with an invalid certificate (expired, self-signed, etc) you can enable the TrustAllCerts switch, like this: PS> .\Get-HTTPStatusCode.ps1 -Url "https://invalidsslserver.example.org/" -Timeout 10 -TrustAllCerts .NOTES Version: 2.2.20220317 Author: Luciano Lingnau, Paessler AG (https://www.paessler.com/) .LINK https://kb.paessler.com/en/topic/47373 #> #Requires -Version 3.0 param( [Parameter(Mandatory=$true)] [string]$Url, [int]$Timeout = "30", [switch]$TrustAllCerts = $false ) [string]$sensorMessage = '' $errorFlag = $false $results = @() #Avoid issues with weird SSL Certificates (Self-signed, expired, etc) #Should only be used when a trusted certificate is not an option if ($TrustAllCerts){ add-type @" using System.Net; using System.Security.Cryptography.X509Certificates; public class TrustAllCertsPolicy : ICertificatePolicy { public bool CheckValidationResult( ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) { return true; } } "@ [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy } try { #Stopwatch used to time the lenghtiest part of the execution (long execution times could be an issue) $exectime = [System.Diagnostics.Stopwatch]::StartNew() $a = Invoke-WebRequest -Uri $Url -TimeoutSec $Timeout -UseBasicParsing -ErrorAction SilentlyContinue #Stop Stopwatch used to time the lenghtiest part of the execution $exectime.Stop() #Parse the results in a PRTG Friendly way if ($a.StatusCode){ $results += @{ Channel = 'Status Code' Value = $a.StatusCode valuelookup = 'prtg.standardlookups.http.statuscode' } $results += @{ Channel = 'Length' Value = $a.RawContentLength } $results += @{ Channel = 'Execution Time' Value = $exectime.ElapsedMilliseconds Unit = 'TimeResponse' } } $sensorMessage = "$($url)" } catch { #If there is a valid statuscode in the response (like 3XX) we want that to be a sensor result, so this has to be handled in the try/catch if ($_.Exception.Response.StatusCode.Value__ -gt 0){ #Parse the results in a PRTG Friendly way $results += @{ Channel = 'Status Code' Value = $_.Exception.Response.StatusCode.Value__ valuelookup = 'prtg.standardlookups.http.statuscode' } $results += @{ Channel = 'Length' Value = '-1' } $results += @{ Channel = 'Execution Time' Value = $exectime.ElapsedMilliseconds Unit = 'TimeResponse' } $sensorMessage = "$($url)" }else{ #Otherwise it's an exception that doesn't have a valid result $errorFlag = $true $sensorMessage = "Exception (Line $($_.InvocationInfo.ScriptLineNumber)): $($_.Exception.Message)" } } $sensorResult = '' | Select-Object prtg if ($errorFlag) { $sensorResult.prtg = '' | Select-Object error $sensorResult.prtg.error = 1 } else { $sensorResult.prtg = '' | Select-Object result $sensorResult.prtg.result = $results } if ($sensorMessage) { $sensorResult.prtg | Add-Member -MemberType NoteProperty -Name 'text' -Value $null $sensorResult.prtg.text = $sensorMessage } $sensorResult | ConvertTo-Json -Depth 5 | Write-Output
In order to pass the url from the sensor's settings, enter it like this in the "Parameters" field:
-Url "https://example.org/" -Timeout 10
Using %host in the parameters as a placeholder like this will also work:
-Url "https://%host/" -Timeout 10
And if you're encountering issues with SSL, try adding TrustAllCerts to the parameters:
-Url "https://%host/" -Timeout 10 -TrustAllCerts
The channel displaying the return code uses an already existing lookup (prtg.standardlookups.http.statuscode) to evaluate which codes are regarded as OK/Warning/Error. Feel free to create a custom lookup based on the existing one if you need.
On a side-note: There's also another lookup called "prtg.standardlookups.http.statuscodedetailed" which contains definitions for every single return code, instead of ranges as in "prtg.standardlookups.http.statuscode".
Changelog:
- 17/03/2022 - Version 2.2 completely changes the code to a more modular approach which is easier to maintain. Functionally almost identic to 1.0
- 09/03/2022 - Version 1.0 includes some bigger changes and is not backwards compatible (the parameters changed slightly). What's new: Invalid certificates are now only accepted when the switch-parameter TrustAllCerts is set. Otherwise you will see an SSL Error. Also fixed a small issue with the units from the ExecTime channel. Added better documentation and examples in the code itself
- 01/09/2021 - Switched from Write-Host to Write-Output to conform with new "PowerShell Security Enhancement" (As of PRTG 21.2.68)
- 25/06/2018 - Modified the try/catch to properly read the status code when it is part of an exception. When this happens, the Length is reported as -1.
- 10/04/2018 - Added code to ignore SSL Certificate errors.
- 28/07/2017 - Included a parameter for timeout. Default = 10 (seconds).
Created on Jan 4, 2017 7:53:50 AM by
Luciano Lingnau [Paessler]
Last change on Mar 17, 2022 4:07:28 PM by
Luciano Lingnau [Paessler]
Hello,
How does it work with https? I have some Login-Sites which i can monitor with this script. I can open them with http and https. on one of the Server,only https is active an the other Servers will follow in time. on the Server with only https i get "Query Failed: Unable to connect to the server", wehne I use the "best Answer" script.
I really need help to monitor the https login
Hi there,
PowerShell is rather picky with its TLS connections. Kindly use the updated version in the best answer, I modified it to support self-signed certificates :)
Kind regards,
Stephan Linke, Tech Support Team
Hi, thank your for providing this script. I have a problem with the script and Windows Server 2019. I get following error when starting it with prtg: This version of %1 is not compatible with the version of Windows you're running. Check your computer's system information and then contact the software publisher. (0xD8)
Does anybody know what to change to make it work?
Thank you in advance
What do your parameters look like and did you check our guide regarding custom PowerShell based Sensors?
Created on Dec 6, 2019 12:19:10 PM by
Stephan Linke [Paessler Support]
Last change on Dec 6, 2019 12:19:16 PM by
Stephan Linke [Paessler Support]
Is the URL available without any authentication? And is that the actual URL? What error do you get?
I´ve found the issue. I had the wrong file extension (not .ps1)
@ Luciano Lingnau,
I've tried using the latest script posted but having an error on PRTG. Any thoughts?
Below is the error though i can ran the script successfully on a device.
Sensor
Custom EXE/Script Sensor
Response not well-formed: "(add-type : (0) : Source file 'C:\windows\TEMP\205ir4ea.0.cs' could not be found (1) : using System.Net; At C:\Program Files (x86)\PRTG Network Monitor\custom sensors\EXE\2_EPHD_URL_Response_Code.ps1:6 char:1 + add-type @" + ~~~~~~~~~~~ + CategoryInfo : InvalidData: (error CS2001: S...ld not be found: CompilerError) [Add-Type], Exception + FullyQualifiedErrorId : SOURCE_CODE_ERROR,Microsoft.PowerShell.Commands. AddTypeCommand add-type : (0) : No source files specified (1) : using System.Net; At C:\Program Files (x86)\PRTG Network Monitor\custom sensors\EXE\2_EPHD_URL_Response_Code.ps1:6 char:1 + add-type @" + ~~~~~~~~~~~ + CategoryInfo : InvalidData: (warning CS2008:...files specified: CompilerError) [Add-Type], Exception + FullyQualifiedErrorId : SOURCE_CODE_ERROR,Microsoft.PowerShell.Commands. AddTypeCommand add-type : Cannot add type. Compilation errors occurred. At C:\Program Files (x86)\PRTG Network Monitor\custom sensors\EXE\2_EPHD_URL_Response_Code.ps1:6 char:1 + add-type @" + ~~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [Add-Type], InvalidOperationExc eption + FullyQualifiedErrorId : COMPILER_ERRORS,Microsoft.PowerShell.Commands.Ad dTypeCommand <prtg> <result> <channel>Status Code</channel> <value>401</value> <valuelookup>prtg.standardlookups.http.statuscodedetailed_401</valuelookup> </result> <result> <channel>Length</channel> <value>-1</value> </result> <result> <channel>ExecTime</channel> <value>58</value> <CustomUnit>msecs</CustomUnit> </result> <text>https://phd.onefluor.com/#/login</text> </prtg> )" (code: PE132)
Created on Nov 6, 2020 12:10:26 AM by
Harold Abubo
(0)
Last change on Nov 6, 2020 8:59:09 AM by
Stephan Linke [Paessler Support]
What's the output of $PSVersiontable (in PowerShell)?
Created on Nov 6, 2020 8:59:57 AM by
Stephan Linke [Paessler Support]
Last change on Nov 6, 2020 9:00:07 AM by
Stephan Linke [Paessler Support]
@Luciano Lingnau thank you for the script it worked very good in my own environment, when I moved the script to the company it did not want to connect to the url because of ssl connection, so I had to add two more lines to the code for it to work ( even adding -TrustAllCerts did not do the trick ).
$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
so the final product is:
param( [Parameter(Mandatory=$true)] [string]$Url, [int]$Timeout = "30", [switch]$TrustAllCerts = $false ) [string]$sensorMessage = '' $errorFlag = $false $results = @() #Avoid issues with weird SSL Certificates (Self-signed, expired, etc) #Should only be used when a trusted certificate is not an option if ($TrustAllCerts){ add-type @" using System.Net; using System.Security.Cryptography.X509Certificates; public class TrustAllCertsPolicy : ICertificatePolicy { public bool CheckValidationResult( ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) { return true; } } "@ $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12' [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy } try { #Stopwatch used to time the lenghtiest part of the execution (long execution times could be an issue) $exectime = [System.Diagnostics.Stopwatch]::StartNew() $a = Invoke-WebRequest -UseBasicParsing -Uri $Url -TimeoutSec $Timeout -ErrorAction SilentlyContinue #Stop Stopwatch used to time the lenghtiest part of the execution $exectime.Stop() #Parse the results in a PRTG Friendly way if ($a.StatusCode){ $results += @{ Channel = 'Status Code' Value = $a.StatusCode valuelookup = 'prtg.standardlookups.http.statuscode' } $results += @{ Channel = 'Execution Time' Value = $exectime.ElapsedMilliseconds Unit = 'TimeResponse' } } $sensorMessage = "$($url)" } catch { #If there is a valid statuscode in the response (like 3XX) we want that to be a sensor result, so this has to be handled in the try/catch if ($_.Exception.Response.StatusCode.Value__ -gt 0){ #Parse the results in a PRTG Friendly way $results += @{ Channel = 'Status Code' Value = $_.Exception.Response.StatusCode.Value__ valuelookup = 'prtg.standardlookups.http.statuscode' } $results += @{ Channel = 'Execution Time' Value = $exectime.ElapsedMilliseconds Unit = 'TimeResponse' } $sensorMessage = "$($url)" }else{ #Otherwise it's an exception that doesn't have a valid result $errorFlag = $true $sensorMessage = "Exception (Line $($_.InvocationInfo.ScriptLineNumber)): $($_.Exception.Message)" } } $sensorResult = '' | Select-Object prtg if ($errorFlag) { $sensorResult.prtg = '' | Select-Object error $sensorResult.prtg.error = 1 } else { $sensorResult.prtg = '' | Select-Object result $sensorResult.prtg.result = $results } if ($sensorMessage) { $sensorResult.prtg | Add-Member -MemberType NoteProperty -Name 'text' -Value $null $sensorResult.prtg.text = $sensorMessage } $sensorResult | ConvertTo-Json -Depth 5 | Write-Output
P.S: I did not understood the need for the Lenght result so I deleted it. I am using theprtg.standardlookups.http.statuscodedetailed lookup and it does wonders, thank you lots!
Hello L3ca,
thank you for your reply and kind feedback!
From what I've seen recently, different powershell versions and host operating systems will have their own nitpicks with SSL endpoints in powershell. I will consider updating the default script to include the code you've suggested :)
And as for the "Length" channel, I've included it because there are probably cases where this is relevant. And because the HTTP Advanced sensor also includes this channel by default(Length). And this sensor is meant as a custom alternative to the HTTP Advanced sensor.
But either way, I'm really happy to hear the code/sensor was helpful to you.
Best Regards,
Luciano Lingnau [Paessler]
Please log in or register to enter your reply.
Add comment