PowerShell Mini Project
In this project you'll build a small but realistic server health report tool, step by step. It's the kind of script operations teams run every morning: read an inventory of servers, combine it with the latest measurements, decide which machines need attention, and produce a report for humans plus machine-readable files for other tools.
It brings together much of the course: CSV and JSON, custom objects, hashtables, advanced functions with validation and pipeline input, error handling, grouping, formatting and scripts with parameters and exit codes.
The finished tool will be used like this:
pwsh -File ./Invoke-HealthReport.ps1 -InventoryPath ./servers.csv -MetricsPath ./metrics.json -CpuLimit 85Each step is a complete program that creates its own sample files, so you can run it on its own.
Step 1: Load the inventory
The inventory is a CSV file maintained by the team. Remember: CSV values are strings, so we convert them into properly typed objects right away.
@'
Name,Role,Location,Cores
web01,frontend,Oslo,4
web02,frontend,Bergen,4
db01,database,Oslo,16
cache01,cache,Oslo,2
batch01,worker,Bergen,8
'@ | Set-Content ./servers.csv
function Import-Inventory {
param([string]$Path)
Import-Csv $Path | ForEach-Object {
[pscustomobject]@{
Name = $_.Name
Role = $_.Role
Location = $_.Location
Cores = [int]$_.Cores
}
}
}
$inventory = Import-Inventory ./servers.csv
"Loaded $($inventory.Count) servers"
$inventory | Format-Table
($inventory | Measure-Object Cores -Sum).SumLoaded 5 servers
Name Role Location Cores
---- ---- -------- -----
web01 frontend Oslo 4
web02 frontend Bergen 4
db01 database Oslo 16
cache01 cache Oslo 2
batch01 worker Bergen 8
34
Step 2: Join with the metrics
A monitoring system exports the latest measurements as JSON. We index them by server name with Group-Object -AsHashTable, so finding a server's metrics is a quick lookup instead of a search. Then we compare each value with a threshold and collect the problems:
@'
Name,Role,Location,Cores
web01,frontend,Oslo,4
web02,frontend,Bergen,4
db01,database,Oslo,16
cache01,cache,Oslo,2
batch01,worker,Bergen,8
'@ | Set-Content ./servers.csv
@'
[
{ "server": "web01", "cpu": 41, "memPct": 63, "diskFreePct": 52 },
{ "server": "web02", "cpu": 93, "memPct": 71, "diskFreePct": 47 },
{ "server": "db01", "cpu": 77, "memPct": 91, "diskFreePct": 6 },
{ "server": "cache01", "cpu": 12, "memPct": 35, "diskFreePct": 80 }
]
'@ | Set-Content ./metrics.json
$inventory = Import-Csv ./servers.csv
$metrics = Get-Content ./metrics.json -Raw | ConvertFrom-Json | Group-Object server -AsHashTable
foreach ($server in $inventory) {
$m = $metrics[$server.Name]
if (-not $m) { "$($server.Name): no data"; continue }
$m = $m[0]
$problems = @()
if ($m.cpu -gt 85) { $problems += "cpu $($m.cpu)%" }
if ($m.memPct -gt 90) { $problems += "memory $($m.memPct)%" }
if ($m.diskFreePct -lt 10) { $problems += "disk $($m.diskFreePct)% free" }
'{0,-8} {1}' -f $server.Name, ($problems ? ($problems -join ', ') : 'healthy')
}web01 healthy
web02 cpu 93%
db01 memory 91%, disk 6% free
cache01 healthy
batch01: no data
It works, but the thresholds are hard-coded and the result is text. Next we turn it into a proper tool that outputs objects.
Step 3: An advanced function
Get-ServerHealth takes inventory objects from the pipeline (binding by property name), has validated thresholds with defaults, outputs one object per server, and warns (instead of failing) when a server has no metrics:
function Get-ServerHealth {
[CmdletBinding()]
param(
[Parameter(Mandatory, ValueFromPipelineByPropertyName)][string]$Name,
[Parameter(ValueFromPipelineByPropertyName)][string]$Role = 'unknown',
[Parameter(Mandatory)][hashtable]$Metrics,
[ValidateRange(1, 100)][int]$CpuLimit = 85,
[ValidateRange(1, 100)][int]$MemLimit = 90,
[ValidateRange(1, 100)][int]$MinDiskFree = 10
)
process {
$m = $Metrics[$Name]
if (-not $m) {
Write-Warning "No metrics for $Name"
return [pscustomobject]@{ Name = $Name; Role = $Role; Status = 'UNKNOWN'; Problems = 'no data' }
}
$m = $m[0]
$problems = @(
if ($m.cpu -gt $CpuLimit) { "cpu $($m.cpu)%" }
if ($m.memPct -gt $MemLimit) { "memory $($m.memPct)%" }
if ($m.diskFreePct -lt $MinDiskFree) { "disk $($m.diskFreePct)% free" }
)
[pscustomobject]@{
Name = $Name
Role = $Role
Status = $problems.Count ? 'ALERT' : 'OK'
Problems = $problems -join ', '
}
}
}
$inventory = @'
Name,Role
web01,frontend
web02,frontend
db01,database
batch01,worker
'@ | ConvertFrom-Csv
$metrics = @'
[ { "server": "web01", "cpu": 41, "memPct": 63, "diskFreePct": 52 },
{ "server": "web02", "cpu": 93, "memPct": 71, "diskFreePct": 47 },
{ "server": "db01", "cpu": 77, "memPct": 91, "diskFreePct": 6 } ]
'@ | ConvertFrom-Json | Group-Object server -AsHashTable
$results = $inventory | Get-ServerHealth -Metrics $metrics
$results | Format-Table
'--- with a stricter CPU limit, only alerts:'
$inventory | Get-ServerHealth -Metrics $metrics -CpuLimit 40 -WarningAction SilentlyContinue |
Where-Object Status -eq 'ALERT' | ForEach-Object Name
try { $inventory | Get-ServerHealth -Metrics $metrics -CpuLimit 150 } catch { 'CpuLimit 150 rejected' }WARNING: No metrics for batch01
Name Role Status Problems
---- ---- ------ --------
web01 frontend OK
web02 frontend ALERT cpu 93%
db01 database ALERT memory 91%, disk 6% free
batch01 worker UNKNOWN no data
--- with a stricter CPU limit, only alerts:
web01
web02
db01
CpuLimit 150 rejected
Because the function outputs objects, the caller can filter, sort and format the results however they like, as the second call shows. -WarningAction SilentlyContinue works because of [CmdletBinding()].
Step 4: Summaries
Managers want numbers: how many servers per status, and which locations are affected. Group-Object and Measure-Object give us that from the same objects:
$health = @(
[pscustomobject]@{ Name = 'web01'; Location = 'Oslo'; Status = 'OK' }
[pscustomobject]@{ Name = 'web02'; Location = 'Bergen'; Status = 'ALERT' }
[pscustomobject]@{ Name = 'db01'; Location = 'Oslo'; Status = 'ALERT' }
[pscustomobject]@{ Name = 'cache01'; Location = 'Oslo'; Status = 'OK' }
[pscustomobject]@{ Name = 'batch01'; Location = 'Bergen'; Status = 'UNKNOWN' }
)
$health | Group-Object Status -NoElement | Sort-Object Count, Name -Descending |
ForEach-Object { '{0,-8} {1}' -f $_.Name, $_.Count }
'--- per location:'
$health | Group-Object Location | Sort-Object Name | ForEach-Object {
$alerts = @($_.Group | Where-Object Status -eq 'ALERT').Count
'{0,-7} {1} servers, {2} alert(s)' -f $_.Name, $_.Count, $alerts
}
$healthyPct = @($health | Where-Object Status -eq 'OK').Count / $health.Count
'Healthy: {0:P0}' -f $healthyPctOK 2
ALERT 2
UNKNOWN 1
--- per location:
Bergen 2 servers, 1 alert(s)
Oslo 3 servers, 1 alert(s)
Healthy: 40 %
Step 5: Write the outputs
The tool produces three files: a CSV for spreadsheets, JSON for other tools (with a timestamp passed in, so the result is reproducible), and a plain-text report built from a here-string template:
$health = @(
[pscustomobject]@{ Name = 'web01'; Role = 'frontend'; Status = 'OK'; Problems = '' }
[pscustomobject]@{ Name = 'web02'; Role = 'frontend'; Status = 'ALERT'; Problems = 'cpu 93%' }
[pscustomobject]@{ Name = 'db01'; Role = 'database'; Status = 'ALERT'; Problems = 'memory 91%, disk 6% free' }
)
$generated = [datetime]'2026-10-17 07:00'
New-Item -ItemType Directory ./out -Force | Out-Null
$health | Export-Csv ./out/health.csv -UseQuotes AsNeeded
[ordered]@{
generated = $generated.ToString('yyyy-MM-ddTHH:mm:ss')
alerts = @($health | Where-Object Status -eq 'ALERT').Count
servers = $health
} | ConvertTo-Json -Depth 3 | Set-Content ./out/health.json
$lines = $health | Where-Object Status -ne 'OK' | ForEach-Object { ' - {0,-6} {1}' -f $_.Name, $_.Problems }
$report = @"
SERVER HEALTH REPORT $($generated.ToString('dddd d MMMM yyyy HH:mm'))
Servers checked: $($health.Count)
Needs attention:
$($lines -join "`n")
"@
Set-Content ./out/report.txt $report
Get-ChildItem ./out -Name
'--- report.txt'
Get-Content ./out/report.txt
'--- health.csv'
Get-Content ./out/health.csv
'--- alerts in health.json'
(Get-Content ./out/health.json -Raw | ConvertFrom-Json).alertshealth.csv
health.json
report.txt
--- report.txt
SERVER HEALTH REPORT Saturday 17 October 2026 07:00
Servers checked: 3
Needs attention:
- web02 cpu 93%
- db01 memory 91%, disk 6% free
--- health.csv
Name,Role,Status,Problems
web01,frontend,OK,
web02,frontend,ALERT,cpu 93%
db01,database,ALERT,"memory 91%, disk 6% free"
--- alerts in health.json
2
Step 6: The finished script
Finally we put everything in a script file with parameters, $ErrorActionPreference = 'Stop', a try/catch around the work, and an exit code a scheduler can check: 0 = all healthy, 1 = alerts, 2 = the tool itself failed. Here the example writes the script to disk and runs it three times:
# --- sample data ---
@'
Name,Role
web01,frontend
web02,frontend
db01,database
'@ | Set-Content ./servers.csv
@'
[ { "server": "web01", "cpu": 41, "memPct": 63, "diskFreePct": 52 },
{ "server": "web02", "cpu": 93, "memPct": 71, "diskFreePct": 47 },
{ "server": "db01", "cpu": 77, "memPct": 88, "diskFreePct": 26 } ]
'@ | Set-Content ./metrics.json
# --- the tool ---
Set-Content ./Invoke-HealthReport.ps1 @'
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$InventoryPath,
[Parameter(Mandatory)][string]$MetricsPath,
[ValidateRange(1, 100)][int]$CpuLimit = 85
)
$ErrorActionPreference = 'Stop'
try {
$metrics = Get-Content $MetricsPath -Raw | ConvertFrom-Json | Group-Object server -AsHashTable
$results = foreach ($s in Import-Csv $InventoryPath) {
$m = $metrics[$s.Name]
$problem = if (-not $m) { 'no data' } elseif ($m[0].cpu -gt $CpuLimit) { "cpu $($m[0].cpu)%" }
[pscustomobject]@{ Name = $s.Name; Status = $problem ? 'ALERT' : 'OK'; Problem = $problem }
}
$alerts = @($results | Where-Object Status -eq 'ALERT')
$results | ForEach-Object { '{0,-6} {1,-5} {2}' -f $_.Name, $_.Status, $_.Problem }
"$($alerts.Count) alert(s) at CPU limit $CpuLimit%"
exit ($alerts.Count ? 1 : 0)
}
catch {
"FAILED: $($_.Exception.Message)"
exit 2
}
'@
& ./Invoke-HealthReport.ps1 -InventoryPath ./servers.csv -MetricsPath ./metrics.json
"exit code: $LASTEXITCODE"
'---'
& ./Invoke-HealthReport.ps1 -InventoryPath ./servers.csv -MetricsPath ./metrics.json -CpuLimit 95
"exit code: $LASTEXITCODE"
'---'
& ./Invoke-HealthReport.ps1 -InventoryPath ./missing.csv -MetricsPath ./metrics.json
"exit code: $LASTEXITCODE"web01 OK
web02 ALERT cpu 93%
db01 OK
1 alert(s) at CPU limit 85%
exit code: 1
---
web01 OK
web02 OK
db01 OK
0 alert(s) at CPU limit 95%
exit code: 0
---
FAILED: Could not find file '/tmp/missing.csv'.
exit code: 2
Ideas to extend the project
- Add
-WhatIf-safe remediation: e.g. aClear-ServerCachefunction withSupportsShouldProcessfor servers whose disk is almost full. - Read the real metrics with
Invoke-RestMethodfrom your monitoring system's API, or withInvoke-Commandfrom the servers themselves. - Turn
Get-ServerHealthand its helpers into a module with a manifest, and add Pester tests. - Send the text report by e-mail or post it to a Teams/Slack webhook (
Invoke-RestMethod -Method Post -Body ($payload | ConvertTo-Json)). - Schedule it with Task Scheduler on Windows or cron on Linux, and alert on exit code 1 or 2.
Test yourself
Why does the tool index the metrics with Group-Object server -AsHashTable?
- To sort them
- To look up each server's metrics by name quickly instead of searching the whole list
- To convert them to CSV
- To remove duplicates
Why does Get-ServerHealth output objects instead of formatted lines?
- Objects are required by Format-Table
- So callers can filter, sort, export or format the results however they need
- Strings can't be piped
- To use less memory
What is the purpose of exit 1 in the finished script?
- It deletes the report
- It tells the caller (a scheduler or CI) that alerts were found
- It restarts the script
- It prints the number 1