Script Probe

Demonstrates a standalone PowerShell script probe measuring latency and producing custom metrics.

Full source

File: pwsh/tutorial/examples/16.2-Health-Script-Probe.ps1

<#
 Script Probe Example
 Demonstrates adding a custom PowerShell script probe with additional data.
#>
param(
    [int]$Port = 5000,
    [IPAddress]$IPAddress = [IPAddress]::Loopback
)

## 1. Logging
New-KrLogger | Add-KrSinkConsole | Register-KrLogger -Name 'console' -SetAsDefault

## 2. Server
New-KrServer -Name 'Health Script Probe'

## 3. Listener (port 5000)
Add-KrEndpoint -Port $Port -IPAddress $IPAddress

#
## 5. Enable configuration
Enable-KrConfiguration

## 6. Script latency probe (random sleep -> classify)
Add-KrHealthProbe -Name 'LatencyCheck' -Tags 'self', 'perf' -ScriptBlock {
    $sw = [System.Diagnostics.Stopwatch]::StartNew()
    Start-Sleep -Milliseconds (Get-Random -Minimum 50 -Maximum 180)
    $sw.Stop()
    $elapsed = $sw.ElapsedMilliseconds
    $status = if ($elapsed -ge 170) { 'Unhealthy' } elseif ($elapsed -ge 130) { 'Degraded' } else { 'Healthy' }
    $data = [Collections.Generic.Dictionary[string, object]]::new()
    $data['elapsedMs'] = $elapsed
    New-KrProbeResult $status "Latency ${elapsed}ms" -Data $data
}

## 7. Health endpoint
Add-KrHealthEndpoint -Pattern '/healthz' -DefaultTags 'self' -ProbeTimeout '00:00:03'

## 8. Start server
Start-KrServer

Step-by-step

  1. Register a script-based probe with Add-KrScriptProbe.
  2. Create a ProbeResult using New-KrProbeResult and include timing metrics.
  3. Assign tags to allow filtering via ?tag=perf.
  4. Start the server and query /healthz.

Try it

Start the script, then:

Invoke-RestMethod http://127.0.0.1:5001/healthz | ConvertTo-Json -Depth 4
Invoke-RestMethod 'http://127.0.0.1:5001/healthz?tag=perf' | ConvertTo-Json -Depth 4

Troubleshooting

Symptom Cause Fix
Probe reports Unhealthy unexpectedly Threshold logic too strict Adjust thresholds or widen degraded window
Missing custom metrics in JSON Data dictionary not populated Ensure you assign keys before returning result

References


Previous / Next

Previous: Health Quickstart Next: HTTP Probe