PowerShell Script Clinic
Documentation: Microsoft Learn
Study a weak pattern, identify the operational risk, then rebuild it around objects, errors, repeatability and verification.
An example to inspect
Preview the example. Sign in for the full lesson and activities.
$servers = Get-Content .\servers.txt
foreach ($server in $servers) {
$os = Get-CimInstance Win32_OperatingSystem -ComputerName $server
Write-Host "$server $($os.Caption)"
}Overview
The first script writes a line of text for each server. The revised version returns named properties and records a failed query alongside successful results.
Fragile inventory script → deliberate automation
Read the smell, then compare a safer pattern. The point is not style; it is predictable behavior under failure.
Before
After
-ErrorAction Stop sends a failed CIM query to catch. Both branches return ComputerName, Caption, and Status so the results can be filtered or exported together. A missing servers.txt file is a separate input error; check the file before starting.
Five questions for every script
Try this review: include one reachable server and one unavailable server in servers.txt. Predict which branch handles each target, then run the script in your test environment. Look for one result per target and an error message on the failed query.
What is the input contract?
Parameters, types, required values and validation.
What objects come out?
Return structured objects before formatting or presentation.
How does failure travel?
Know which errors terminate, what gets logged and what the caller sees.
Can I run it twice?
Prefer state-aware, idempotent behavior for automation.
How do I prove success?
Verify resulting state, not only a zero exit path.
Explain your own script
Paste code into the line-by-line teaching tool.
Review your script
Text-based review hints only. This does not execute or fully validate PowerShell.