PowerShell Project: Monitoring System
A monitoring system is a script that checks the health of things and writes a report. Each check gives one verdict, and the report file gathers the verdicts.
Check whether a file exists
Test each file name and print present or missing. The verdict is a word, not a file listing.
Set-Content -Path "data.txt" -Value "one"
if (Test-Path "data.txt") { "data.txt: present" } else { "data.txt: missing" }
if (Test-Path "gone.txt") { "gone.txt: present" } else { "gone.txt: missing" }Read a state from a file
A state file holds one word for the state. Read the word and compare it with the healthy state.
Set-Content -Path "service.txt" -Value "running"
$state = Get-Content -Path "service.txt"
if ($state -eq "running") { "Service: running" } else { "Service: stopped" }Turn a count into a warning with a threshold
Count the lines in the queue file. Compare the count with a limit of 3 to decide the verdict.
Set-Content -Path "queue.txt" -Value @("a", "b", "c", "d")
$count = (Get-Content -Path "queue.txt").Count
"Items: " + $count
if ($count -gt 3) { "Queue: warning" } else { "Queue: OK" }Example
Set-Content -Path "data.txt" -Value @("one", "two", "three")
Set-Content -Path "service.txt" -Value "running"
Set-Content -Path "queue.txt" -Value @("a", "b", "c", "d")
$report = @()
if (Test-Path "data.txt") { $report += "data.txt: present" } else { $report += "data.txt: missing" }
$state = Get-Content -Path "service.txt"
if ($state -eq "running") { $report += "service: running" } else { $report += "service: stopped" }
$count = (Get-Content -Path "queue.txt").Count
$report += "queue items: " + $count
if ($count -gt 3) { $report += "queue: warning" } else { $report += "queue: OK" }
Set-Content -Path "report.txt" -Value $report
Get-Content -Path "report.txt"Key points
- Health check: A health check is one test that returns a verdict about one thing.
- File check: A file check tests whether a needed file exists.
- State file: A state file is a small file whose text names the state of something, such as running or stopped.
- Threshold: A threshold is a limit that turns a count into a warning when the count passes it.
- Report file: A report file is a text file that gathers one verdict line per check.
In this example, the script first creates the three files it will check, so the checks run on known data. It checks the data file, reads the service state, and counts the queue against a limit of 3. It gathers one verdict line per check into a report file and prints the report.
Note
The report shows verdicts only, so it stays readable at a glance.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A monitoring script counts 4 items in a queue with a warning limit of 3. What verdict should it record for the queue?