PowerShell Genie

PowerShell Script Clinic

Guide 2 min read Windows PowerShell 5.1 and PowerShell 7

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)"
}
Review a script

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

1PS> $servers = Get-Content .\servers.txt
2PS> foreach ($server in $servers) {
3PS> $os = Get-CimInstance Win32_OperatingSystem -ComputerName $server
4PS> Write-Host "$server $($os.Caption)"
5PS> }

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.

1PS> $servers = Get-Content .\servers.txt
2PS> foreach ($server in $servers) {
3PS> try {
4PS> $osParams = @{
5PS> ComputerName = $server
6PS> ErrorAction = 'Stop'
7PS> }
8PS> $os = Get-CimInstance Win32_OperatingSystem @osParams
9PS> [pscustomobject]@{
10PS> ComputerName = $server
11PS> Caption = $os.Caption
12PS> Status = 'OK'
13PS> }
14PS> }
15PS> catch {
16PS> [pscustomobject]@{
17PS> ComputerName = $server
18PS> Caption = $null
19PS> Status = $_.Exception.Message
20PS> }
21PS> }
22PS> }

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.

    Continue
    Genie guidePowerShell Script Clinic

    Study a weak pattern, identify the operational risk, then rebuild it around objects, errors, repeatability and verification.