Real-World PowerShell Scripts
Build a disk usage report, a safe old-file cleanup and an API health monitor in PowerShell, then schedule them with Task Scheduler, cron or a systemd timer.
By The Dark DebuggerUpdated 37 min read
This is the capstone of the PowerShell track. We build three scripts that you could drop onto a server tonight: a disk usage report that writes CSV and HTML, a cleanup script that deletes old files safely, and an API health monitor that retries, writes a JSON status file and fails loudly. Then we schedule them with Task Scheduler, cron and systemd. It assumes you have worked through advanced functions, error handling, files and folders, CSV and JSON and REST APIs, and that you have PowerShell 7 installed.
Why unattended scripts are different
A script that works at your desk can fail in new ways at 02:30 when a scheduler runs it. Nobody reads the console. The working directory is not your project folder. PATH is minimal. And the classic trap: an error prints in red, the script carries on, exits with code 0, and the scheduler records a success. You find out three weeks later when the disk fills up.
So every script in this article follows the same rules:
| Rule | How the scripts do it | Covered in |
|---|---|---|
| Validate input before doing anything | param() with [ValidateScript()] and [ValidateRange()] | Functions |
| Stop on the first unexpected error | Set-StrictMode -Version Latest and $ErrorActionPreference = 'Stop' | Error handling |
| Expected problems are recorded, not fatal | -ErrorAction SilentlyContinue -ErrorVariable | Error handling |
| Destructive actions can be rehearsed | SupportsShouldProcess, -WhatIf, -Confirm | Functions |
| Results are machine-readable | Export-Csv, ConvertTo-Html, ConvertTo-Json | CSV, JSON, and XML |
| Success or failure is in the exit code | exit 0 or exit 1 at the end | Scripts and modules |
A practice server to work on
Deleting files is not something to practise on your real home directory. This script builds a fake application server under ./srv: 60 days of API logs, two weeks of database backups, four releases, uploads, a thumbnail cache and some scratch files, each with a realistic last-write time.
# New-DemoData.ps1 - builds a fake application server tree to practise on.
param([string]$Root = './srv')
$now = Get-Date
function New-DemoFile {
param([string]$Path, [long]$Size, [double]$AgeDays, [datetime]$LastWrite = $now.AddDays(-$AgeDays))
$null = New-Item -ItemType Directory -Path (Split-Path -Path $Path -Parent) -Force
$stream = [System.IO.File]::Create($Path)
$stream.SetLength($Size) # allocate without writing data
$stream.Close()
(Get-Item -LiteralPath $Path).LastWriteTime = $LastWrite
}
# 60 days of daily API logs, 1-3 MB each, last written just before midnight
foreach ($age in 0..59) {
$day = $now.Date.AddDays(-$age)
$lastWrite = if ($age -eq 0) { $now } else { $day.AddHours(23).AddMinutes(59) }
New-DemoFile "$Root/logs/api-$($day.ToString('yyyy-MM-dd')).log" (1MB + ($age % 3) * 1MB) -LastWrite $lastWrite
}
# Nightly database backups for the last 14 days
foreach ($age in 0..13) {
$day = $now.AddDays(-$age).ToString('yyyy-MM-dd')
New-DemoFile "$Root/backups/orders-db-$day.bak" (12MB + $age * 256KB) $age
}
# Four releases of the application, each a little bigger than the last
$releaseAges = [ordered]@{ '2026.09.14' = 56; '2026.10.05' = 35; '2026.10.26' = 14; '2026.11.06' = 3 }
$extra = 0
foreach ($release in $releaseAges.GetEnumerator()) {
$dir = "$Root/app/releases/$($release.Key)"
New-DemoFile "$dir/Orders.Api.dll" (17MB + $extra) $release.Value
foreach ($n in 1..6) { New-DemoFile "$dir/lib/dep$n.dll" 900KB $release.Value }
$extra += 400KB
}
# User uploads, thumbnail cache and scratch files
foreach ($n in 1..40) { New-DemoFile "$Root/uploads/invoice-$('{0:d4}' -f $n).pdf" (200KB + $n * 17KB) ($n * 2) }
foreach ($n in 1..400) { New-DemoFile "$Root/cache/thumbs/t$n.jpg" 12KB ($n % 20) }
foreach ($n in 1..25) { New-DemoFile "$Root/tmp/upload-$n.tmp" 350KB ($n * 3 + 1) }
"Created $((Get-ChildItem -LiteralPath $Root -Recurse -File).Count) files under $Root"./New-DemoData.ps1Created 567 files under ./srvSetLength makes a file of the right size without writing any data. On Linux's ext4 those files are sparse, so the 437 MB tree took almost no real disk space in my lab. On NTFS, expect the space to be allocated, so delete ./srv when you are done.
Real servers always have a folder your account cannot read, so I added one. On Linux:
mkdir -p srv/private && echo secret > srv/private/keys.txt && chmod 000 srv/privateOn Windows, the same situation is a folder whose ACL denies you. All three scripts sit next to each other in one folder, and every command below is run from that folder.
Script 1: a disk usage report in CSV and HTML
The question "where did the disk go?" comes up on every server eventually. This script answers it per top-level folder, lists the biggest files, records free space, and writes a CSV (for spreadsheets and for comparing runs) and an HTML page (for people).
#Requires -Version 7.2
<#
.SYNOPSIS
Reports disk usage per top-level folder and writes CSV and HTML reports.
.DESCRIPTION
Sums every file under each top-level folder of -Path, lists the largest
files and the free space on the volume. Folders that cannot be read are
reported as warnings instead of stopping the run.
.EXAMPLE
./Get-FolderUsage.ps1 -Path /srv/app -OutputDirectory ./reports
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateScript({ Test-Path -LiteralPath $_ -PathType Container })]
[string]$Path,
[string]$OutputDirectory = './reports',
[ValidateRange(1, 50)]
[int]$Top = 5
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$root = (Resolve-Path -LiteralPath $Path).ProviderPath
$stamp = Get-Date -Format 'yyyy-MM-dd_HHmm'
$null = New-Item -ItemType Directory -Path $OutputDirectory -Force
# One recursive walk; unreadable folders land in $readErrors instead of stopping us.
$allFiles = @(Get-ChildItem -LiteralPath $root -File -Recurse -Force `
-ErrorAction SilentlyContinue -ErrorVariable readErrors)
foreach ($err in $readErrors) {
Write-Warning "Skipped (no access): $([IO.Path]::GetRelativePath($root, $err.TargetObject))"
}
$totalBytes = [long]($allFiles | Measure-Object -Property Length -Sum).Sum
$folders = $allFiles |
Group-Object -Property {
$parts = [IO.Path]::GetRelativePath($root, $_.FullName) -split '[\\/]'
if ($parts.Count -gt 1) { $parts[0] } else { '(top level)' }
} |
ForEach-Object {
$bytes = ($_.Group | Measure-Object -Property Length -Sum).Sum
[pscustomobject]@{
Folder = $_.Name
SizeMB = [math]::Round($bytes / 1MB, 1)
Percent = [math]::Round(100 * $bytes / [math]::Max($totalBytes, 1), 1)
Files = $_.Count
Newest = ($_.Group | Measure-Object -Property LastWriteTime -Maximum).Maximum.ToString('yyyy-MM-dd')
}
} |
Sort-Object -Property SizeMB -Descending
$largest = $allFiles | Sort-Object -Property Length -Descending | Select-Object -First $Top |
Select-Object @{ Name = 'File'; Expression = { [IO.Path]::GetRelativePath($root, $_.FullName) } },
@{ Name = 'SizeMB'; Expression = { [math]::Round($_.Length / 1MB, 1) } },
@{ Name = 'LastWrite'; Expression = { $_.LastWriteTime.ToString('yyyy-MM-dd') } }
$drive = (Get-Item -LiteralPath $root).PSDrive
$freeGB = [math]::Round($drive.Free / 1GB, 1)
$sizeGB = [math]::Round(($drive.Used + $drive.Free) / 1GB, 1)
$totalMB = [math]::Round($totalBytes / 1MB, 1)
# CSV for spreadsheets and for comparing runs.
$csvPath = Join-Path -Path $OutputDirectory -ChildPath "folder-usage_$stamp.csv"
$folders | Export-Csv -LiteralPath $csvPath -NoTypeInformation -Encoding utf8
# HTML for people. -Title is ignored when -Head is used, so <title> goes in the head.
$encodedPath = [System.Net.WebUtility]::HtmlEncode($Path)
$head = @"
<title>Disk usage: $encodedPath</title>
<style>
body { font-family: Segoe UI, Arial, sans-serif; margin: 2em; color: #222; }
table { border-collapse: collapse; margin-bottom: 1.5em; }
th, td { border: 1px solid #ccc; padding: 4px 10px; text-align: left; }
th { background: #eee; }
</style>
"@
$pre = "<h1>Disk usage: $encodedPath</h1>" +
"<p>$totalMB MB in $($allFiles.Count) files. Volume: $freeGB GB free of $sizeGB GB. " +
"Generated $(Get-Date -Format 'yyyy-MM-dd HH:mm').</p><h2>By folder</h2>"
$post = $largest | ConvertTo-Html -Fragment -PreContent "<h2>Largest $Top files</h2>"
if ($readErrors) {
$post += "<p><strong>Warning:</strong> $($readErrors.Count) folder(s) could not be read.</p>"
}
$htmlPath = Join-Path -Path $OutputDirectory -ChildPath "folder-usage_$stamp.html"
$folders | ConvertTo-Html -Head $head -PreContent $pre -PostContent $post |
Set-Content -LiteralPath $htmlPath -Encoding utf8
Write-Host "Total: $totalMB MB in $($allFiles.Count) files; volume free: $freeGB GB of $sizeGB GB"
Write-Host "Reports: $csvPath, $htmlPath"
$foldersThe parts worth slowing down for:
- One walk, errors collected.
-ErrorAction SilentlyContinue -ErrorVariable readErrorsturns "permission denied" from a red error (or, withStop, a crash) into a list we report at the end. Everything else still stops the script, because$ErrorActionPreferenceisStop. - Grouping by a computed key.
Group-Objecttakes a script block. We take the path relative to the root and split it on either slash with the regex[\\/], so the same code works with Windows and Linux paths.[IO.Path]::GetRelativePath()is .NET Core only, which is one reason for#Requires -Version 7.2. - Free space from the provider.
(Get-Item $root).PSDrivegives theC:orD:drive on Windows. On Linux, PowerShell has a single/drive, so the figure is for the root filesystem. If your data lives on a separate mount, check it withdf -h. - The script emits objects. The folder rows go to the pipeline, so the caller decides how to display them, or pipes them somewhere else.
Run it:
./Get-FolderUsage.ps1 -Path ./srv | Format-TableWARNING: Skipped (no access): private
Total: 436.8 MB in 567 files; volume free: 951.5 GB of 1006.9 GB
Reports: ./reports/folder-usage_2026-11-10_0134.csv, ./reports/folder-usage_2026-11-10_0134.html
Folder SizeMB Percent Files Newest
------ ------ ------- ----- ------
backups 190.80 43.70 14 2026-11-10
logs 120.00 27.50 60 2026-11-10
app 91.40 20.90 28 2026-11-07
uploads 21.40 4.90 40 2026-11-08
tmp 8.50 2.00 25 2026-11-06
cache 4.70 1.10 400 2026-11-10Why | Format-Table? An object with five or more properties is displayed as a list by default, one block per folder. The table is easier to scan. The 400 thumbnails in cache take less space than 14 backups; file counts and sizes tell very different stories, so the report shows both.
The CSV is plain and diff-friendly:
Get-Content ./reports/folder-usage_*.csv"Folder","SizeMB","Percent","Files","Newest"
"backups","190.8","43.7","14","2026-11-10"
"logs","120","27.5","60","2026-11-10"
"app","91.4","20.9","28","2026-11-07"
"uploads","21.4","4.9","40","2026-11-08"
"tmp","8.5","2","25","2026-11-06"
"cache","4.7","1.1","400","2026-11-10"The HTML file opens in any browser: a heading with the totals, the folder table, a "Largest 5 files" table (the four Orders.Api.dll builds at 17 to 18.2 MB, then a 15.2 MB backup) and the warning about the unreadable folder. ConvertTo-Html HTML-encodes property values for you (a folder named R&D becomes R&D in the table), but text you pass to -PreContent goes in raw. That is why the script encodes $Path itself before putting it in the heading.
Script 2: deleting old files without regret
Log and temp cleanup is the most common scheduled script there is, and the most dangerous. A wrong path or a wrong number deletes things you needed. The defences: refuse obviously bad input, support -WhatIf so you can rehearse, log every decision, and return a non-zero exit code when something failed.
#Requires -Version 7.2
<#
.SYNOPSIS
Deletes files older than N days that match the given patterns, with a log.
.DESCRIPTION
Supports -WhatIf and -Confirm. Every decision is appended to a log file,
including during a -WhatIf dry run. Exits with code 1 if any delete failed.
.EXAMPLE
./Remove-StaleFile.ps1 -Path /srv/app -OlderThanDays 30 -WhatIf
#>
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
param(
[Parameter(Mandatory)]
[ValidateScript({ Test-Path -LiteralPath $_ -PathType Container })]
[string]$Path,
[Parameter(Mandatory)]
[ValidateRange(1, 3650)]
[int]$OlderThanDays,
[string[]]$Include = @('*.log', '*.tmp'),
[string]$LogPath = "./logs/cleanup-$(Get-Date -Format 'yyyy-MM').log"
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
function Write-Log {
param(
[Parameter(Mandatory)][string]$Message,
[ValidateSet('INFO', 'WARN', 'ERROR')][string]$Level = 'INFO'
)
$line = '{0} [{1}] {2}' -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $Level, $Message
# Logging is not the risky action: never skip it for -WhatIf or prompt for it.
Add-Content -LiteralPath $LogPath -Value $line -WhatIf:$false -Confirm:$false
Write-Verbose $line
}
$root = (Resolve-Path -LiteralPath $Path).ProviderPath
if ($root -eq [IO.Path]::GetPathRoot($root)) {
throw "Refusing to clean the root of a volume: $root"
}
$logDir = Split-Path -Path $LogPath -Parent
if ($logDir) { $null = New-Item -ItemType Directory -Path $logDir -Force -WhatIf:$false -Confirm:$false }
$cutoff = (Get-Date).AddDays(-$OlderThanDays)
$mode = if ($WhatIfPreference) { 'DRY RUN' } else { 'DELETE' }
Write-Log ("Start {0}: path={1} cutoff={2:yyyy-MM-dd HH:mm} include={3}" -f
$mode, $Path, $cutoff, ($Include -join ','))
$candidates = @(Get-ChildItem -LiteralPath $root -File -Recurse -Include $Include `
-ErrorAction SilentlyContinue -ErrorVariable readErrors |
Where-Object LastWriteTime -lt $cutoff)
foreach ($err in $readErrors) {
Write-Log -Level WARN "Could not read $([IO.Path]::GetRelativePath($root, $err.TargetObject))"
}
$deleted = 0
$failed = 0
[long]$freedBytes = 0
foreach ($file in $candidates) {
$relative = [IO.Path]::GetRelativePath($root, $file.FullName)
$ageDays = [math]::Round(((Get-Date) - $file.LastWriteTime).TotalDays, 1)
if ($PSCmdlet.ShouldProcess($relative, "Delete file last written $ageDays days ago")) {
try {
# -Confirm:$false: we already asked once through ShouldProcess.
Remove-Item -LiteralPath $file.FullName -Force -Confirm:$false
$deleted++
$freedBytes += $file.Length
Write-Log "Deleted $relative ($ageDays days, $($file.Length) bytes)"
}
catch {
$failed++
Write-Log -Level ERROR "Failed $relative - $($_.CategoryInfo.Reason)"
}
}
else {
$verb = if ($WhatIfPreference) { 'Would delete' } else { 'Declined' }
Write-Log "$verb $relative ($ageDays days, $($file.Length) bytes)"
}
}
$summary = [pscustomobject]@{
Mode = $mode
Matched = $candidates.Count
Deleted = $deleted
Failed = $failed
FreedMB = [math]::Round($freedBytes / 1MB, 1)
}
Write-Log ("Done: matched={0} deleted={1} failed={2} freedMB={3}" -f
$summary.Matched, $deleted, $failed, $summary.FreedMB)
$summary
exit ([int]($failed -gt 0))How the safety features work:
SupportsShouldProcessgives the script-WhatIfand-Confirmfor free.$PSCmdlet.ShouldProcess(target, action)is the gate: under-WhatIfit prints a "What if" line and returns$false, and under-Confirmit asks. Put every destructive call inside thatif.- The switches leak into everything.
-WhatIfand-Confirmset$WhatIfPreferenceand$ConfirmPreferencefor the whole script, includingAdd-ContentandNew-Item. My first version only had-WhatIf:$falseon the logging calls. When I tested-Confirm, PowerShell asked me to confirm creating the log folder and then every single log line. Leaving-Confirm:$falseoffRemove-Itemadds a second prompt per file: my "Delete file" prompt, thenRemove-Item's own "Remove File" prompt. Hence-WhatIf:$false -Confirm:$falseon the logging calls and-Confirm:$falseinside the gate. - Guard rails. The root of a volume is refused outright,
-OlderThanDaysmust be between 1 and 3650, and-Pathmust be an existing folder. - Relative paths in the log. The start line records the path as given, and each file line is relative to it, so the log stays readable.
- Exit code.
exit 1if any delete failed, so a scheduler can tell.
Always rehearse first:
./Remove-StaleFile.ps1 -Path ./srv -OlderThanDays 30 -WhatIfWhat if: Performing the operation "Delete file last written 58.1 days ago" on target "logs/api-2026-09-12.log".
What if: Performing the operation "Delete file last written 57.1 days ago" on target "logs/api-2026-09-13.log".
[…]
What if: Performing the operation "Delete file last written 30.1 days ago" on target "logs/api-2026-10-10.log".
What if: Performing the operation "Delete file last written 31 days ago" on target "tmp/upload-10.tmp".
[…]
What if: Performing the operation "Delete file last written 76 days ago" on target "tmp/upload-25.tmp".
Mode : DRY RUN
Matched : 45
Deleted : 0
Failed : 0
FreedMB : 0The log for 2026-10-10 is 30.1 days old because the demo logs are last written at 23:59, so it just makes the cut. The 2026-10-11 log, at 29.1 days, stays. When the list looks right, run it for real:
./Remove-StaleFile.ps1 -Path ./srv -OlderThanDays 30Mode : DELETE
Matched : 45
Deleted : 45
Failed : 0
FreedMB : 64.5The log has both runs, including the folder it could not read:
Get-Content ./logs/cleanup-2026-11.log2026-11-10 01:34:41 [INFO] Start DRY RUN: path=./srv cutoff=2026-10-11 01:34 include=*.log,*.tmp
2026-11-10 01:34:41 [WARN] Could not read private
2026-11-10 01:34:41 [INFO] Would delete logs/api-2026-09-12.log (58.1 days, 3145728 bytes)
[…]
2026-11-10 01:34:41 [INFO] Done: matched=45 deleted=0 failed=0 freedMB=0
2026-11-10 01:34:42 [INFO] Start DELETE: path=./srv cutoff=2026-10-11 01:34 include=*.log,*.tmp
2026-11-10 01:34:42 [WARN] Could not read private
2026-11-10 01:34:42 [INFO] Deleted logs/api-2026-09-12.log (58.1 days, 3145728 bytes)
[…]
2026-11-10 01:34:42 [INFO] Deleted tmp/upload-25.tmp (76 days, 358400 bytes)
2026-11-10 01:34:42 [INFO] Done: matched=45 deleted=45 failed=0 freedMB=64.5A second run reported Matched 0. That matters for scheduled jobs, which must be safe to run twice.
With -Confirm you get exactly one prompt per file. To test it in a script, I piped the answers in, so the Y appears after the prompt:
printf 'Y\nY\nY\n' | pwsh -NoProfile -File ./Remove-StaleFile.ps1 -Path ./confirm-test/data -OlderThanDays 30 -LogPath ./confirm-test/c.log -ConfirmConfirm
Are you sure you want to perform this action?
Performing the operation "Delete file last written 40 days ago" on target
"a.log".
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help
(default is "Y"):YNow a failure. I made logs/archive read-only (chmod 555) and put three 90-day-old logs in it. Run from bash, the way a scheduler would:
pwsh -NoProfile -File ./Remove-StaleFile.ps1 -Path ./srv -OlderThanDays 30
echo "exit code: $?"
tail -5 logs/cleanup-2026-11.logMode : DELETE
Matched : 3
Deleted : 0
Failed : 3
FreedMB : 0
exit code: 1
2026-11-10 01:34:44 [WARN] Could not read private
2026-11-10 01:34:44 [ERROR] Failed logs/archive/api-2026-07.log - UnauthorizedAccessException
2026-11-10 01:34:44 [ERROR] Failed logs/archive/api-2026-08.log - UnauthorizedAccessException
2026-11-10 01:34:44 [ERROR] Failed logs/archive/api-2026-09.log - UnauthorizedAccessException
2026-11-10 01:34:44 [INFO] Done: matched=3 deleted=0 failed=3 freedMB=0The script kept going after the first failure, logged each one, and still exited with 1. And the guard rail:
try { ./Remove-StaleFile.ps1 -Path / -OlderThanDays 30 -WhatIf } catch { $_.Exception.Message }Refusing to clean the root of a volume: /Script 3: an API health monitor with retries
The third chore is "is the service actually up?". A useful monitor retries before it cries wolf, treats a hang as a failure, writes its result somewhere a dashboard can read, and exits non-zero so whatever runs it can alert. To test it without real services, I wrote a small stand-in API in Python. It has one healthy service, one that returns 503 twice while "starting", one that always returns 500, and one that hangs for six seconds:
# fake_api.py - stand-in services for testing the health monitor
import json
import sys
import time
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
inventory_calls = 0
class Handler(BaseHTTPRequestHandler):
def reply(self, code, body):
data = json.dumps(body).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def do_GET(self):
global inventory_calls
if self.path == "/orders/health":
self.reply(200, {"status": "ok"})
elif self.path == "/inventory/health": # still starting: 503 twice, then OK
inventory_calls += 1
if inventory_calls <= 2:
self.reply(503, {"status": "starting"})
else:
self.reply(200, {"status": "ok"})
elif self.path == "/billing/health": # broken
self.reply(500, {"status": "error", "detail": "db pool exhausted"})
elif self.path == "/reports/health": # hangs longer than the timeout
time.sleep(6)
self.reply(200, {"status": "ok"})
elif self.path == "/catalog/health": # slow but working
time.sleep(1.5)
self.reply(200, {"status": "ok"})
else:
self.reply(404, {"status": "not found"})
ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), Handler).serve_forever()python3 fake_api.py 8771 2>api-server.log &
API_PID=$!The endpoints live in a config file, not in the script, so adding a service never means editing code. search-api points at a port where nothing listens:
{
"timeoutSec": 3,
"maxAttempts": 3,
"retryDelaySec": 2,
"endpoints": [
{ "name": "orders-api", "url": "http://127.0.0.1:8771/orders/health", "expectStatus": 200 },
{ "name": "inventory-api", "url": "http://127.0.0.1:8771/inventory/health", "expectStatus": 200 },
{ "name": "billing-api", "url": "http://127.0.0.1:8771/billing/health", "expectStatus": 200 },
{ "name": "reports-api", "url": "http://127.0.0.1:8771/reports/health", "expectStatus": 200 },
{ "name": "search-api", "url": "http://127.0.0.1:8779/health", "expectStatus": 200 }
]
}The monitor:
#Requires -Version 7.2
<#
.SYNOPSIS
Checks the HTTP endpoints listed in a JSON file and writes a JSON status file.
.DESCRIPTION
Each endpoint gets up to maxAttempts tries with a growing delay between them.
Exit code 0 = all endpoints healthy, 1 = at least one unhealthy.
.EXAMPLE
./Test-ApiHealth.ps1 -ConfigPath ./endpoints.json -StatusPath ./status/api-health.json
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateScript({ Test-Path -LiteralPath $_ -PathType Leaf })]
[string]$ConfigPath,
[string]$StatusPath = './status/api-health.json'
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
function Test-Endpoint {
param(
[Parameter(Mandatory)][string]$Name,
[Parameter(Mandatory)][string]$Url,
[int]$ExpectStatus = 200,
[int]$TimeoutSec = 5,
[int]$MaxAttempts = 3,
[int]$RetryDelaySec = 2
)
$attempt = 0
do {
$attempt++
$statusCode = $null
$problem = $null
$timer = [System.Diagnostics.Stopwatch]::StartNew()
try {
$response = Invoke-WebRequest -Uri $Url -TimeoutSec $TimeoutSec -SkipHttpErrorCheck
$statusCode = [int]$response.StatusCode
if ($statusCode -ne $ExpectStatus) { $problem = "HTTP $statusCode" }
}
catch {
# DNS failures, refused connections and timeouts end up here.
$problem = $_.Exception.Message
}
$timer.Stop()
if ($problem -and $attempt -lt $MaxAttempts) {
$delay = $RetryDelaySec * $attempt
Write-Verbose "${Name}: attempt $attempt failed ($problem); retrying in ${delay}s"
Start-Sleep -Seconds $delay
}
} while ($problem -and $attempt -lt $MaxAttempts)
[pscustomobject]@{
Name = $Name
Healthy = -not $problem
StatusCode = $statusCode
Attempts = $attempt
LatencyMs = $timer.ElapsedMilliseconds
Error = $problem
}
}
$config = Get-Content -LiteralPath $ConfigPath -Raw | ConvertFrom-Json
$results = foreach ($endpoint in $config.endpoints) {
$splat = @{
Name = $endpoint.name
Url = $endpoint.url
ExpectStatus = $endpoint.expectStatus
TimeoutSec = $config.timeoutSec
MaxAttempts = $config.maxAttempts
RetryDelaySec = $config.retryDelaySec
}
Test-Endpoint @splat
}
$unhealthy = @($results | Where-Object { -not $_.Healthy })
$status = [ordered]@{
checkedAt = Get-Date -AsUTC -Format 'o'
healthy = $unhealthy.Count -eq 0
summary = '{0} of {1} endpoints healthy' -f ($results.Count - $unhealthy.Count), $results.Count
checks = $results
}
# Write to a temporary file and rename it, so a dashboard never reads half a file.
$statusDir = Split-Path -Path $StatusPath -Parent
if ($statusDir) { $null = New-Item -ItemType Directory -Path $statusDir -Force }
$status | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath "$StatusPath.tmp" -Encoding utf8
Move-Item -LiteralPath "$StatusPath.tmp" -Destination $StatusPath -Force
Write-Host "$($status.summary) - status written to $StatusPath"
$results | Format-Table -Property Name, Healthy, StatusCode, Attempts, LatencyMs, Error
exit ([int]($unhealthy.Count -gt 0))The design decisions:
-SkipHttpErrorCheck(PowerShell 7) returns 4xx and 5xx responses as normal responses, so a 500 is a status code we compare, not an exception. Only transport failures reachcatch: refused connections, DNS errors and timeouts.-TimeoutSecturns a hung service into a failure after 3 seconds. Without it, one hung service can stall the whole run.- Linear backoff. Wait 2 seconds, then 4. A service that is restarting gets time to come back before we call it down.
- Atomic write.
Set-Contentto a.tmpfile followed byMove-Item -Forcemeans a reader sees the old file or the new one, never half of one. $ProgressPreference = 'SilentlyContinue'keeps progress bars out of logs.
Why not use the built-in -MaximumRetryCount? I tested it against both kinds of failure:
$timer = [Diagnostics.Stopwatch]::StartNew()
try {
Invoke-WebRequest -Uri http://127.0.0.1:8779/health -MaximumRetryCount 3 -RetryIntervalSec 2
}
catch { "Failed after $($timer.ElapsedMilliseconds) ms: $($_.Exception.Message)" }
$timer.Restart()
$r = Invoke-WebRequest -Uri http://127.0.0.1:8771/billing/health -MaximumRetryCount 3 -RetryIntervalSec 2 -SkipHttpErrorCheck
"HTTP $($r.StatusCode) after $($timer.ElapsedMilliseconds) ms"Failed after 273 ms: Connection refused (127.0.0.1:8779)
HTTP 500 after 6105 msThe 500 was retried three times, 2 seconds apart. The refused connection was not retried at all. With -Verbose, that call printed a single WebRequest: v1.1 GET line. A service that is down hard, which is the case you most want to retry, gets one attempt. The manual loop treats every failure the same way and tells us how many attempts it took.
Run the monitor with -Verbose to watch the retries:
./Test-ApiHealth.ps1 -ConfigPath ./endpoints.json -VerboseVERBOSE: WebRequest: v1.1 GET http://127.0.0.1:8771/orders/health
VERBOSE: WebResponse: 200 OK with application/json payload with body size 16 B (16 bytes)
VERBOSE: WebRequest: v1.1 GET http://127.0.0.1:8771/inventory/health
VERBOSE: WebResponse: 503 Service Unavailable with application/json payload with body size 22 B (22 bytes)
VERBOSE: inventory-api: attempt 1 failed (HTTP 503); retrying in 2s
VERBOSE: WebRequest: v1.1 GET http://127.0.0.1:8771/inventory/health
VERBOSE: WebResponse: 503 Service Unavailable with application/json payload with body size 22 B (22 bytes)
VERBOSE: inventory-api: attempt 2 failed (HTTP 503); retrying in 4s
VERBOSE: WebRequest: v1.1 GET http://127.0.0.1:8771/inventory/health
VERBOSE: WebResponse: 200 OK with application/json payload with body size 16 B (16 bytes)
[…]
2 of 5 endpoints healthy - status written to ./status/api-health.json
Name Healthy StatusCode Attempts LatencyMs Error
---- ------- ---------- -------- --------- -----
orders-api True 200 1 109
inventory-api True 200 3 8
billing-api False 500 3 3 HTTP 500
reports-api False 3 3005 The request was canceled d…
search-api False 3 3 Connection refused (127.0.…inventory-api was healthy on the third attempt, which is exactly the "still starting" case retries exist for. The table cuts long errors off; the JSON file has them in full:
{
"checkedAt": "2026-11-10T12:12:54.5612444Z",
"healthy": false,
"summary": "2 of 5 endpoints healthy",
"checks": [
[…]
{
"Name": "reports-api",
"Healthy": false,
"StatusCode": null,
"Attempts": 3,
"LatencyMs": 3005,
"Error": "The request was canceled due to the configured HttpClient.Timeout of 3 seconds elapsing."
},
[…]
]
}What a scheduler sees is the exit code:
pwsh -NoProfile -File ./Test-ApiHealth.ps1 -ConfigPath ./endpoints.json
echo "exit code: $?"2 of 5 endpoints healthy - status written to ./status/api-health.json
[…]
search-api False 3 3 Connection refused (127.0.…
exit code: 1Called from another PowerShell script, the same number lands in $LASTEXITCODE:
./Test-ApiHealth.ps1 -ConfigPath ./endpoints.json | Out-Null; $LASTEXITCODE2 of 5 endpoints healthy - status written to ./status/api-health.json
1Out-Null swallowed the table but not the Write-Host line, because Write-Host writes to the information stream, not the output pipeline. When you are done testing, stop the stand-in API with kill "$API_PID".
Scheduling the scripts
A script nobody runs is a script that does not exist. The three schedulers below all do the same job. The things that differ are where they start your script, which environment it gets, and where its output goes.
Windows: Task Scheduler
This is what I would run on a Windows server. I did not run it, because registering tasks on the machine I test on is off limits. I checked every cmdlet and parameter name against Get-Command -Syntax in Windows PowerShell 5.1.
# Run in an elevated PowerShell session. Assumes the scripts live in D:\ops.
$pwsh = 'C:\Program Files\PowerShell\7\pwsh.exe'
# Health monitor every 5 minutes, as NETWORK SERVICE (needs write access to D:\ops\status).
$action = New-ScheduledTaskAction -Execute $pwsh -WorkingDirectory 'D:\ops' `
-Argument '-NoProfile -NonInteractive -ExecutionPolicy Bypass -File "D:\ops\Test-ApiHealth.ps1" -ConfigPath "D:\ops\endpoints.json"'
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).Date -RepetitionInterval (New-TimeSpan -Minutes 5)
$settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Minutes 4) `
-MultipleInstances IgnoreNew -StartWhenAvailable
$principal = New-ScheduledTaskPrincipal -UserId 'NT AUTHORITY\NETWORK SERVICE' -LogonType ServiceAccount
Register-ScheduledTask -TaskPath '\Ops\' -TaskName 'API health monitor' -Action $action `
-Trigger $trigger -Settings $settings -Principal $principal `
-Description 'Checks API health endpoints and writes D:\ops\status\api-health.json'
# Nightly maintenance at 02:30 as SYSTEM, because it deletes files.
$nightly = New-ScheduledTaskAction -Execute $pwsh -WorkingDirectory 'D:\ops' `
-Argument '-NoProfile -NonInteractive -ExecutionPolicy Bypass -File "D:\ops\Invoke-NightlyMaintenance.ps1" -AppRoot "D:\apps\orders"'
Register-ScheduledTask -TaskPath '\Ops\' -TaskName 'Nightly maintenance' -Action $nightly `
-Trigger (New-ScheduledTaskTrigger -Daily -At '02:30') -User 'NT AUTHORITY\SYSTEM' -RunLevel HighestThe details that bite people:
- Full path to
pwsh.exe.powershell.exeis Windows PowerShell 5.1, and these scripts declare#Requires -Version 7.2. -NonInteractivemakes a strayRead-Hostor confirmation prompt fail immediately instead of hanging the task until its time limit.-ExecutionPolicy Bypassapplies only to that one process. Signing your scripts is the stricter option; the trade-offs are in Scripts and modules.- Working directory. Without
-WorkingDirectory, a task starts inC:\Windows\System32, and every relative path in your script points there. The nightly wrapper below also doesSet-Location $PSScriptRootas a second line of defence. - The exit code becomes "Last Run Result".
Get-ScheduledTaskInfo -TaskPath '\Ops\' -TaskName 'API health monitor'exposes it asLastTaskResult. For our monitor it would be 1 whenever an endpoint was down, which your existing Windows monitoring can alert on.
Linux: cron
cron runs commands through /bin/sh with a tiny PATH and no terminal. These are the crontab lines (edit with crontab -e) for the same two jobs:
*/5 * * * * cd /opt/ops && NO_COLOR=1 /usr/bin/pwsh -NoProfile -File ./Test-ApiHealth.ps1 -ConfigPath ./endpoints.json >> ./logs/health-cron.log 2>&1
30 2 * * * cd /opt/ops && NO_COLOR=1 /usr/bin/pwsh -NoProfile -File ./Invoke-NightlyMaintenance.ps1 >> ./logs/nightly-cron.log 2>&1I tested the health monitor line with * * * * * (so I did not have to wait five minutes) and with my lab's paths, because pwsh is installed under my home directory there instead of /usr/bin. After the next minute ticked over, the log had the run:
cat ./logs/health-cron.log2 of 5 endpoints healthy - status written to ./status/api-health.json
Name Healthy StatusCode Attempts LatencyMs Error
---- ------- ---------- -------- --------- -----
orders-api True 200 1 79
inventory-api True 200 1 15
billing-api False 500 3 10 HTTP 500
reports-api False 3 3004 The request was canceled d…
search-api False 3 7 Connection refused (127.0.…Then I removed the entries again. Three things make this line work: the cd (cron starts in your home directory), the full path to pwsh (see Common mistakes), and NO_COLOR=1, which keeps colour escape codes out of the log file. cron ignores exit codes unless you act on them. The status file, or the systemd setup below, is how you notice a failure.
Linux: a systemd timer
systemd timers give you what cron does not: a record of every run, its exit code and its output in the journal. A user-level unit needs no root. Two files go in ~/.config/systemd/user/:
# pwsh-api-health.service
[Unit]
Description=API health monitor (PowerShell)
[Service]
Type=oneshot
WorkingDirectory=/opt/ops
Environment=NO_COLOR=1
ExecStart=/usr/bin/pwsh -NoProfile -File ./Test-ApiHealth.ps1 -ConfigPath ./endpoints.json# pwsh-api-health.timer
[Unit]
Description=Run the API health monitor every 5 minutes
[Timer]
OnCalendar=*:0/5
AccuracySec=10s
Persistent=true
[Install]
WantedBy=timers.targetAs with cron, my lab copy used %h/... paths in place of /opt/ops and /usr/bin/pwsh; everything else was identical. AccuracySec=10s stops systemd from delaying the run by up to its default of one minute. Enable the timer:
systemctl --user daemon-reload
systemctl --user enable --now pwsh-api-health.timerCreated symlink /home/sid/.config/systemd/user/timers.target.wants/pwsh-api-health.timer → /home/sid/.config/systemd/user/pwsh-api-health.timer.You can trigger the service immediately to test it. Because our script exits with 1, systemd reports a failure, which is what we want:
systemctl --user start pwsh-api-health.service
systemctl --user show pwsh-api-health.service -p Result -p ExecMainStatusJob for pwsh-api-health.service failed because the control process exited with error code.
See "systemctl --user status pwsh-api-health.service" and "journalctl --user -xeu pwsh-api-health.service" for details.
Result=exit-code
ExecMainStatus=1The journal holds the script's output followed by systemd's verdict:
journalctl --user -u pwsh-api-health.service -o cat --no-pager -n 20[…]
2 of 5 endpoints healthy - status written to ./status/api-health.json
Name Healthy StatusCode Attempts LatencyMs Error
[…]
pwsh-api-health.service: Main process exited, code=exited, status=1/FAILURE
pwsh-api-health.service: Failed with result 'exit-code'.
Failed to start pwsh-api-health.service - API health monitor (PowerShell).
pwsh-api-health.service: Consumed 2.512s CPU time.The trimmed parts surprised me. PowerShell on Linux writes its own diagnostics to syslog, so every web error the script caught also appeared in the journal as a multi-line Command_Health warning block. They are harmless, but filter for the unit's own lines when you read the journal.
At the next five-minute mark the timer fired on its own. LAST shows when:
systemctl --user list-timers pwsh-api-health.timer --no-pagerNEXT LEFT LAST PASSED UNIT ACTIVATES
Tue 2026-11-10 01:35:00 EST 4min 16s Tue 2026-11-10 01:30:02 EST 41s ago pwsh-api-health.timer pwsh-api-health.service
1 timers listed.
Pass --all to see loaded but inactive timers, too.To remove it, which I did straight after:
systemctl --user disable --now pwsh-api-health.timer
rm ~/.config/systemd/user/pwsh-api-health.service ~/.config/systemd/user/pwsh-api-health.timer
systemctl --user daemon-reloadUser timers only run while your user's systemd instance is running. On a real server, install the units as system units under /etc/systemd/system/ with a User= line, or enable lingering for the account. The Bash track covers both schedulers in more depth in System Monitoring and Scheduling with cron and systemd.
Where you'll use this
The three scripts map directly onto jobs that exist on almost every team:
| Job | Script | Typical setup |
|---|---|---|
| IIS or application log retention on Windows servers | Remove-StaleFile.ps1 | -Path C:\inetpub\logs\LogFiles -Include *.log -OlderThanDays 30, nightly |
| "Why is the D: drive full?" tickets on file servers | Get-FolderUsage.ps1 | Weekly HTML report emailed or published to a share |
| Post-deployment smoke test in CI | Test-ApiHealth.ps1 | A pipeline step; the non-zero exit fails the deploy (see the Jenkins capstone) |
| Uptime checks with no monitoring product | Test-ApiHealth.ps1 | Every 5 minutes; a dashboard reads the JSON status file |
| The same checks across a fleet | Any of them | Run through Invoke-Command against many servers, covered in Remoting and jobs |
On a real server you rarely schedule three separate jobs. You schedule one nightly wrapper that runs them in order, keeps a transcript, and reports one exit code:
#Requires -Version 7.2
# Invoke-NightlyMaintenance.ps1 - cleanup, usage report and health check, one log per night.
[CmdletBinding()]
param([string]$AppRoot = './srv')
$ErrorActionPreference = 'Stop'
Set-Location -LiteralPath $PSScriptRoot # schedulers start you somewhere else
$runLog = "./logs/nightly-$(Get-Date -Format 'yyyy-MM-dd').log"
$null = Start-Transcript -LiteralPath $runLog -Append -UseMinimalHeader
$failures = @()
try {
./Remove-StaleFile.ps1 -Path $AppRoot -OlderThanDays 30 | Format-Table
if ($LASTEXITCODE -ne 0) { $failures += 'cleanup' }
./Get-FolderUsage.ps1 -Path $AppRoot -OutputDirectory ./reports | Format-Table
./Test-ApiHealth.ps1 -ConfigPath ./endpoints.json
if ($LASTEXITCODE -ne 0) { $failures += 'health' }
}
catch {
$failures += "crashed: $($_.Exception.Message)"
}
finally {
"Nightly run finished. Failures: $(if ($failures) { $failures -join ', ' } else { 'none' })"
$null = Stop-Transcript
}
exit ([int]($failures.Count -gt 0))pwsh -NoProfile -File ./Invoke-NightlyMaintenance.ps1
echo "exit code: $?"Mode Matched Deleted Failed FreedMB
---- ------- ------- ------ -------
DELETE 3 3 0 0.00
WARNING: Skipped (no access): private
Total: 372.4 MB in 522 files; volume free: 951.5 GB of 1006.9 GB
Reports: ./reports/folder-usage_2026-11-10_0713.csv, ./reports/folder-usage_2026-11-10_0713.html
[…]
logs 61.00 16.40 31 2026-11-10
[…]
2 of 5 endpoints healthy - status written to ./status/api-health.json
[…]
Nightly run finished. Failures: health
exit code: 1The three deleted files are the read-only archive logs from the failure test, which I had made writable again. Logs dropped from 120 MB to 61 MB after the earlier cleanup. The transcript in logs/nightly-2026-11-10.log captured the same text, plus one thing the console did not show. It recorded a PS>TerminatingError(Invoke-WebRequest): "Connection refused" line for every web error the monitor caught internally. That is useful when you debug, but alarming if you don't expect it. -UseMinimalHeader keeps the transcript header to a start time, without the user, machine name and host details it otherwise records.
Common mistakes
cron cannot find pwsh
The first crontab line I tested used plain pwsh, as I would type it in a terminal. The log contained only this:
cat ./logs/cron-bad.log/bin/sh: 1: pwsh: not foundcron's PATH is usually just /usr/bin:/bin. Wherever pwsh lives, write its full path in the crontab line. Find it with command -v pwsh.
-WhatIf silently switched off the log
I made a copy of the script, Remove-StaleFile-bad.ps1, without -WhatIf:$false on the Add-Content call. Then I did a dry run against a folder with one old file. PowerShell printed What if: Performing the operation "Add Content" on target "Path: …/mistake/cleanup.log" three times. The log file was never created:
./Remove-StaleFile-bad.ps1 -Path ./mistake -OlderThanDays 30 -LogPath ./mistake/cleanup.log -WhatIf | Out-Null; Test-Path ./mistake/cleanup.log[…]
What if: Performing the operation "Delete file last written 40 days ago" on target "logs/old.log".
[…]
FalseThe -WhatIf you pass to a script applies to every cmdlet in it that supports ShouldProcess. A dry run that writes no log is a dry run you cannot review. Opt the bookkeeping out with -WhatIf:$false -Confirm:$false, and leave the real deletions inside $PSCmdlet.ShouldProcess().
Colour codes in your log files
PowerShell 7 colours table headers even when output is redirected to a file:
pwsh -NoProfile -File ./Test-ApiHealth.ps1 -ConfigPath ./endpoints.json > color.log 2>&1
grep -c $'\e' color.log
sed -n '3,4p' color.log | cat -v2
^[[32;1mName ^[[0m^[[32;1m Healthy^[[0m^[[32;1m StatusCode^[[0m^[[32;1m Attempts^[[0m^[[32;1m LatencyMs^[[0m^[[32;1m Error^[[0m
^[[32;1m---- ^[[0m ^[[32;1m-------^[[0m ^[[32;1m----------^[[0m ^[[32;1m--------^[[0m ^[[32;1m---------^[[0m ^[[32;1m-----^[[0mSetting NO_COLOR=1 in the environment makes PowerShell switch $PSStyle.OutputRendering to PlainText. The same command then wrote 0 escape sequences. Use it in cron lines and unit files, or set $PSStyle.OutputRendering = 'PlainText' at the top of the script.
Numbers from Import-Csv sort as text
Every value Import-Csv returns is a string, so this sorts alphabetically:
Import-Csv ./reports/folder-usage_2026-11-10_0134.csv | Sort-Object -Property SizeMB -Descending | Format-Table Folder, SizeMBFolder SizeMB
------ ------
app 91.4
tmp 8.5
cache 4.7
uploads 21.4
backups 190.8
logs 120"91.4" sorts above "190.8" because "9" comes after "1". Cast in a calculated sort key, Sort-Object -Property { [double]$_.SizeMB } -Descending, and the same file comes out as backups, logs, app, uploads, tmp, cache. Any script that compares two reports needs the same cast before it subtracts.
Summary
- Unattended scripts need four things a desk script can skip: validated parameters, stop-on-error by default, a log or machine-readable output, and an exit code that reflects success.
- Collect expected problems with
-ErrorAction SilentlyContinue -ErrorVariable nameand report them. Let everything else stop the script. [CmdletBinding(SupportsShouldProcess)]plus$PSCmdlet.ShouldProcess()gives you-WhatIfand-Confirm. Both leak into every cmdlet in the script, so opt logging out and use-Confirm:$falseinside the gate.Invoke-WebRequest -SkipHttpErrorCheck -TimeoutSecseparates HTTP errors from transport failures.-MaximumRetryCountretried HTTP 500s but not refused connections, so write your own retry loop when "service down" matters.- Write status files atomically (temporary file, then
Move-Item -Force), and keep configuration such as endpoints in a JSON file next to the script. - Schedulers start you in a different directory with a different
PATH: use full paths to pwsh, set the working directory orSet-Location $PSScriptRoot, and setNO_COLOR=1for clean logs. - Task Scheduler shows the exit code as Last Run Result, and systemd marks the unit failed. cron does neither, so pair it with a status file.
Exercises
Write Get-ApiStatus.ps1 that reads ./status/api-health.json and prints one line per unhealthy endpoint (name, attempts, error), or All endpoints healthy. Add one safety check: if the file is older than 10 minutes, print a warning. A dead monitor stops updating the file, and a stale "all healthy" looks exactly like a real one.
Hint
ConvertFrom-Json gives you objects you can filter with Where-Object. For the age, (Get-Item $path).LastWriteTime is simpler than parsing checkedAt.
Show Solution
param(
[string]$StatusPath = './status/api-health.json',
[int]$MaxAgeMinutes = 10
)
$file = Get-Item -LiteralPath $StatusPath
$ageMinutes = [math]::Round(((Get-Date) - $file.LastWriteTime).TotalMinutes, 1)
if ($ageMinutes -gt $MaxAgeMinutes) {
Write-Warning "Status file is $ageMinutes minutes old - is the monitor still running?"
}
$status = Get-Content -LiteralPath $StatusPath -Raw | ConvertFrom-Json
$down = @($status.checks | Where-Object { -not $_.Healthy })
if ($down.Count -eq 0) {
'All endpoints healthy'
}
foreach ($check in $down) {
'{0} DOWN after {1} attempt(s): {2}' -f $check.Name, $check.Attempts, $check.Error
}Straight after a monitor run:
./Get-ApiStatus.ps1billing-api DOWN after 3 attempt(s): HTTP 500
reports-api DOWN after 3 attempt(s): The request was canceled due to the configured HttpClient.Timeout of 3 seconds elapsing.
search-api DOWN after 3 attempt(s): Connection refused (127.0.0.1:8779)To test the stale check, I moved the file's timestamp into the past with (Get-Item ./status/api-health.json).LastWriteTime = (Get-Date).AddMinutes(-25):
WARNING: Status file is 25 minutes old - is the monitor still running?
billing-api DOWN after 3 attempt(s): HTTP 500
[…]After Remove-StaleFile.ps1 deletes old logs, folders such as logs/archive/2026-08 can be left empty. Extend the script so it also removes empty directories under -Path, honours -WhatIf and -Confirm, logs each removal and leaves unreadable folders alone.
Hint
Process directories deepest first (sort by the length of FullName, descending) and check emptiness inside the loop, not before it. Then a parent that only contained an empty child is empty by the time you reach it.
Show Solution
Insert this just before $summary = [pscustomobject]@{:
# Remove directories the cleanup left empty, deepest first.
$directories = Get-ChildItem -LiteralPath $root -Directory -Recurse -ErrorAction SilentlyContinue |
Sort-Object -Property { $_.FullName.Length } -Descending
foreach ($dir in $directories) {
try { $children = @(Get-ChildItem -LiteralPath $dir.FullName -Force) }
catch { continue } # unreadable: leave it alone
if ($children.Count -gt 0) { continue }
$relative = [IO.Path]::GetRelativePath($root, $dir.FullName)
if ($PSCmdlet.ShouldProcess($relative, 'Remove empty directory')) {
Remove-Item -LiteralPath $dir.FullName -Confirm:$false
Write-Log "Removed empty directory $relative"
}
}I tested it on a tree where logs/archive/2026-08 held three logs from August. The real run logged:
2026-11-10 07:14:30 [WARN] Could not read private
2026-11-10 07:14:30 [INFO] Deleted logs/archive/2026-08/api-2026-08-01.log (101 days, 3 bytes)
2026-11-10 07:14:30 [INFO] Deleted logs/archive/2026-08/api-2026-08-02.log (100 days, 3 bytes)
2026-11-10 07:14:30 [INFO] Deleted logs/archive/2026-08/api-2026-08-03.log (99 days, 3 bytes)
2026-11-10 07:14:30 [INFO] Removed empty directory logs/archive/2026-08
2026-11-10 07:14:30 [INFO] Removed empty directory logs/archive
2026-11-10 07:14:30 [INFO] Done: matched=3 deleted=3 failed=0 freedMB=0Both levels went, deepest first. The unreadable private folder made the inner Get-ChildItem throw, so it was skipped. One limitation: under -WhatIf the files are not really deleted, so the dry run cannot predict which folders would become empty. The dry run I did listed the three files and no directories.
A health endpoint that answers in 1.5 seconds is up, but something is wrong. Let each endpoint in the JSON config have an optional maxLatencyMs. Report a State of Up, Degraded (healthy but slower than its limit) or Down. Degraded endpoints must not change the exit code. Test it with the stand-in API's /catalog/health, which takes 1.5 seconds.
Hint
The script runs under Set-StrictMode -Version Latest. Reading $endpoint.maxLatencyMs on an endpoint that does not define it throws. Check $endpoint.PSObject.Properties['maxLatencyMs'] first.
Show Solution
Add [int]$MaxLatencyMs = 0 to the param() block of Test-Endpoint, and compute the state before building the result object:
$state = if ($problem) { 'Down' }
elseif ($MaxLatencyMs -gt 0 -and $timer.ElapsedMilliseconds -gt $MaxLatencyMs) { 'Degraded' }
else { 'Up' }
[pscustomobject]@{
Name = $Name
State = $state
Healthy = -not $problem
StatusCode = $statusCode
Attempts = $attempt
LatencyMs = $timer.ElapsedMilliseconds
Error = $problem
}In the main loop, pass the limit only when it exists:
# Under Set-StrictMode, reading a property that is not in the JSON throws.
if ($endpoint.PSObject.Properties['maxLatencyMs']) {
$splat.MaxLatencyMs = $endpoint.maxLatencyMs
}
Test-Endpoint @splatThen change the Format-Table line to show State instead of Healthy. With a config where orders-api has a 500 ms limit, catalog-api has 1000 ms, and billing-api has none:
./Test-ApiHealth.ps1 -ConfigPath ./endpoints-latency.json2 of 3 endpoints healthy - status written to ./status/api-health.json
Name State StatusCode Attempts LatencyMs Error
---- ----- ---------- -------- --------- -----
orders-api Up 200 1 88
catalog-api Degraded 200 1 1505
billing-api Down 500 2 3 HTTP 500The exit code was still 1, because of billing-api only. Without the PSObject.Properties check, the run died on billing-api with The property 'maxLatencyMs' cannot be found on this object. Verify that the property exists.
A single usage report tells you where the space is. Two reports tell you where it is going. Write Compare-FolderUsage.ps1 with -Before and -After parameters (two CSV files from Get-FolderUsage.ps1). It should output one row per folder with BeforeMB, AfterMB and ChangeMB, sorted by growth, and handle folders that appear or disappear between the reports.
Hint
Load the "before" file into a hashtable keyed by folder name, then walk the "after" file. Remember that Import-Csv gives you strings.
Show Solution
param(
[Parameter(Mandatory)][string]$Before,
[Parameter(Mandatory)][string]$After
)
# Import-Csv returns strings; cast sizes to [double] before doing maths or sorting.
$old = @{}
foreach ($row in Import-Csv -LiteralPath $Before) { $old[$row.Folder] = [double]$row.SizeMB }
$seen = @{}
$rows = foreach ($row in Import-Csv -LiteralPath $After) {
$seen[$row.Folder] = $true
$was = if ($old.ContainsKey($row.Folder)) { $old[$row.Folder] } else { 0 }
[pscustomobject]@{
Folder = $row.Folder
BeforeMB = $was
AfterMB = [double]$row.SizeMB
ChangeMB = [math]::Round([double]$row.SizeMB - $was, 1)
}
}
$gone = foreach ($folder in $old.Keys) {
if (-not $seen.ContainsKey($folder)) {
[pscustomobject]@{ Folder = $folder; BeforeMB = $old[$folder]; AfterMB = 0; ChangeMB = -$old[$folder] }
}
}
@($rows) + @($gone) | Sort-Object -Property ChangeMB -DescendingI compared the first report of the day with one taken after the cleanups, a new 16 MB backup and a new exports folder:
./Compare-FolderUsage.ps1 -Before ./reports/before.csv -After ./reports/after.csv | Format-TableFolder BeforeMB AfterMB ChangeMB
------ -------- ------- --------
exports 0 27.00 27.00
backups 190.80 206.80 16.00
[…]
tmp 8.50 3.10 -5.40
logs 120.00 61.00 -59.00Report file names include the minute (folder-usage_2026-11-10_0134.csv), so two runs in the same minute overwrite each other. Give each run its own -OutputDirectory if you script comparisons like this.
Tested with: PowerShell 7.6.9 on Ubuntu 24.04 (WSL2), November 2026. Every script, run and exercise solution above was executed as shown against the generated ./srv tree and the local Python stand-in API, and the outputs are pasted from those runs (long output trimmed where marked). The cron entry and the systemd user timer were installed, observed firing, and removed again; the lab used paths under my home directory instead of /opt/ops and /usr/bin/pwsh. The Windows Task Scheduler block was not executed: I only checked its cmdlet names, parameter names and enum values with Get-Command in Windows PowerShell 5.1 (5.1.26100) and parsed it without errors. Two things surprised me while testing: -MaximumRetryCount does not retry refused connections, and PowerShell under systemd writes its own Command_Health warnings to the journal.
Written by The Dark Debugger
Engineer documenting the things that took me too long to learn, so they take you less time. Every PowerShell tutorial here is tested end to end before publishing.