Skip to content

Latest commit

Β 

History

108 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ“‘ PrtgSensorKit

PowerShell framework for building PRTG custom EXE/Script Advanced sensors - less boilerplate, valid JSON output every time.

License: MIT Version Platform Built with ModuleBuilder


You write the logic that gathers your metrics; PrtgSensorKit handles building the channels, formatting the JSON PRTG expects, capping channels/message length, and reporting errors.

✨ Why PrtgSensorKit

  • 🧱 No boilerplate - build channels with one cmdlet, emit valid PRTG JSON with another, or wrap the whole sensor in Invoke-PrtgSensor.
  • βœ… Always-valid output - enforces PRTG's rules for you (max 50 channels, no #, 2000-char messages, 0/1 flags).
  • πŸͺ† Pipe-friendly - chain New-PrtgChannel | Add-PrtgChannel with no intermediate variables.
  • πŸ”€ Runtime helpers - jump to 64-bit PowerShell or PowerShell 7+ when your sensor needs it.
  • πŸ” Secret storage - keep API tokens and credentials out of your script, DPAPI-encrypted.
  • πŸ’Ύ State between runs - cache values and compute rates/deltas, safe under overlapping scans.
  • 🀝 Shared collection cache - many sensors share one expensive API/SQL/WMI call per interval, race-free.
  • πŸ” Retries and TLS - -RetryCount re-runs flaky blocks, -ForceModernTls fixes 5.1's web request defaults.
  • πŸ“ File logging - per-run log files with full error details, without ever touching the sensor output.
  • 🩺 Sensor doctor - finds the classic sensor-script mistakes before PRTG does; debug interactively with -DryRun.
  • πŸ“– Full built-in help - every command is documented; Get-Help <command> -Full.

πŸ“¦ Install

# From Windows PowerShell 5.1 (elevated) - PRTG runs sensors there
Install-Module PrtgSensorKit -Scope AllUsers

PRTG launches sensors in 32-bit Windows PowerShell 5.1 as a service account, which decides where PrtgSensorKit and your sensor's dependency modules must be installed. Details and the host/bitness matrix: Installation.

πŸš€ Your first PRTG sensor

Save this as an EXE/Script Advanced sensor script in C:\Program Files (x86)\PRTG Network Monitor\Custom Sensors\EXEXML\.

Put your channel-building logic in a script block and Invoke-PrtgSensor handles the rest - it catches errors and turns them into a PRTG error response, keeps stray output from corrupting the result (see the warning below), and emits exactly one valid response:

Import-Module PrtgSensorKit

Invoke-PrtgSensor {
  $cpuUsage = Get-Process |
    ForEach-Object { $_.CPU } |
    Measure-Object -Average |
    Select-Object -ExpandProperty Average

  New-PrtgChannel -Channel 'CPU Usage' -Value $cpuUsage -Unit Percent -Float | Add-PrtgChannel
  Set-PrtgMessage 'CPU usage average'
}

Your script's param() values and other script-scope variables are visible inside the block, so sensors that take parameters work unchanged:

param([string]$ApiUrl, [string]$ApiToken)

Import-Module PrtgSensorKit

Invoke-PrtgSensor {
  $response = Invoke-RestMethod -Uri $ApiUrl -Headers @{ Authorization = "Bearer $ApiToken" }
  $response.data | ForEach-Object { New-PrtgChannel -Channel $_.name -Value $_.value -Unit $_.unit | Add-PrtgChannel }
  Set-PrtgMessage $response.message
}

Tip

Always quote placeholders in PRTG's "Parameters" field: -ApiUrl '%host', not -ApiUrl %host. A device name or placeholder value containing a space otherwise shifts every positional argument, and the sensor fails in ways that are hard to trace back.

Warning

⚠️ Never write to the output stream in your sensor code. PRTG reads the sensor result from the process standard output, which must contain only the JSON. A stray Write-Host, a bare Write-Output, or an un-captured command that returns objects (e.g. Get-Process on its own line) will corrupt the result. Invoke-PrtgSensor discards that output for you. To debug, log to a file - add -EnableLogging to the Invoke-PrtgSensor call and use Write-PrtgLog (see File logging) - never log to output.

Making web requests? Windows PowerShell 5.1 often lacks TLS 1.2 by default; add -ForceModernTls (see Resilience).

Starting a new sensor? Copy 01-basic-single-channel.ps1 as your template - the numbered examples build up from there.

πŸ“š Documentation

Topic What's in it
Installation Where the module and your dependencies go: hosts, bitness, AllUsers scope
Channels Units, floats, limits - and why limits only apply at sensor creation
Runtime hosts Restart-As64BitPowershell / Restart-InPwsh and import ordering
Credentials and secrets DPAPI storage, the account-binding trap, saving as Local System
State between runs Rates, deltas, histories; locking and retention
Shared collection cache One expensive call shared by many sensors, exactly one fetch per interval
File logging Per-run log files, lifecycle logging, retention
Resilience Retries for flaky sources, modern TLS on 5.1
Diagnosing and debugging The sensor doctor and -DryRun
Custom errors and low-level output Non-terminating errors, manual output control

❓ Getting help on any command

Every command ships with full PowerShell comment-based help. You don't need this README to look up a parameter; ask PowerShell directly:

Get-Help New-PrtgChannel              # summary, syntax, and description
Get-Help New-PrtgChannel -Full        # every parameter explained, plus notes
Get-Help New-PrtgChannel -Examples    # just the runnable examples
Get-Help New-PrtgChannel -Parameter Unit   # help for one parameter

Tip

-Full is the one to reach for while writing a sensor - it lists every unit, limit, and lookup parameter with a description. This works for all commands below.

🧰 Commands

Main Commands

Command Purpose
Invoke-PrtgSensor Run a sensor block with boilerplate, error handling, and output hygiene handled
New-PrtgChannel Build a channel object
Add-PrtgChannel Add a channel to the sensor output (max 50)
Set-PrtgMessage Set the sensor message
Get-PrtgMessage Get the current sensor message
Save-PrtgSecret Store an API token or credential, DPAPI-encrypted
Get-PrtgSecret Read a stored secret in a sensor
Save-PrtgSensorState Persist a value between sensor runs
Get-PrtgSensorState Read state saved by a previous run
Clear-PrtgSensorState Delete or prune stored sensor state
Use-PrtgCachedResult Share one expensive call across sensors (TTL cache, race-free)
Write-PrtgLog Append a timestamped line to this run's log file
Restart-As64BitPowershell Re-launch the sensor in 64-bit PowerShell
Restart-InPwsh Re-launch the sensor in PowerShell 7+
Invoke-PrtgSensorDoctor Diagnose common issues in a sensor script

Lower-level Commands (advanced)

Command Purpose
Write-PrtgOutput Emit the sensor JSON
Write-PrtgError Emit a PRTG error response
Clear-PrtgOutput Clear channels and message
Set-PrtgOutput Hand-roll your own sensor output object

See Custom errors and low-level output before using the lower-level commands directly.

πŸ› οΈ Building from source

./tasks.ps1 install_dev_requirements   # ModuleBuilder, Configuration, Pester, PSScriptAnalyzer
./tasks.ps1 lint                       # PSScriptAnalyzer style + 5.1/7.0 compatibility checks
./tasks.ps1 build                      # builds Source/ to ./Dist
./tasks.ps1 test                       # builds, then runs the Pester suite against Source/
./tasks.ps1 test -Target Dist          # same suite, importing the built module instead
./tasks.ps1 coverage                   # builds, then coverage per source file
./tasks.ps1 prepare_release 1.1.0      # gates + changelog check, stamps version, verified rebuild

Work done here with coding agents follows Vibe Driven Development.

πŸ“„ License

Released under the MIT License.

About

PowerShell framework for building PRTG custom sensors - less boilerplate, valid output every time.

Topics

Resources

Stars

12 stars

Watchers

1 watching

Forks

Releases

Used by

Contributors

Languages