Projects Level: Advanced Chapter 18: PowerShell Automation Projects

Handle errors and finish

Error handling is your plan for what a tool does when something goes wrong. You test edge cases, warn clearly, and finish with version notes and a sharing checklist.

Lesson 4 of 4 in Chapter 18: PowerShell Automation Projects. Previous step in this path: Schedule and run it safely. 3 learning objectives, 5 examples, and a knowledge check.

Start: what you will learn

Error handling is your plan for what a tool does when something goes wrong. You test edge cases, warn clearly, and finish with version notes and a sharing checklist.

Learning objectives

  • Explain try, catch, and finally in simple terms
  • Choose between Write-Error and Write-Warning
  • Test edge cases and finish with version notes and a sharing checklist

Concept in simple words

What it is: Error handling is code that plans for failure instead of hoping it never happens. A try block holds the work that might fail. A catch block holds what to do if it fails. A finally block holds cleanup that should run either way, such as closing a file or writing a closing note. An edge case is an unusual input, such as an empty list, a missing file, or a permission problem, that is rare but completely normal in real work.

Why it works

Why it exists: Real admin work meets missing files, empty results, and permission limits, every week. Without a plan, the tool stops with a confusing message, or worse, it keeps going with wrong data and produces a report that looks fine but is not true. With a plan, the tool explains the problem in plain words, stops safely where it should, and leaves the system in a clean state, so the next run starts from a known place.

What PowerShell does with terminating and nonterminating errors: This split is the key to the whole lesson. A terminating error stops the current work at once, and catch can handle it. A nonterminating error reports a problem but lets the work continue, and catch will not catch it on its own. Many file and service commands report nonterminating errors by default. That is why -ErrorAction Stop matters so much. It turns a nonterminating error into a terminating error for that one command, so catch can handle it.

What the flow looks like, step by step: PowerShell runs the try block from top to bottom. If every line succeeds, the catch block is skipped, and the finally block runs. If a line in try produces a terminating error, PowerShell jumps at once to the catch block, and it skips the rest of the try block after the failing line. After catch finishes, the finally block runs. Finally runs on success and on failure, so it is the right place for cleanup, not for the main result.

What finally is for, and what it is not for: Finally is for work that must happen either way. Examples are closing a file, writing a closing log line, or clearing a temporary value. Finally is not the place for your main report, and it is not the place to decide if the job succeeded. If you put the main result in finally, it will appear even when the job failed, and the reader may think a failed run succeeded.

What the error object gives you: Inside catch, the automatic variable $_ holds the current error object. The part $_.Exception.Message holds the plain words message for that error, such as a file not found note. Using that message in your own error text helps the reader fix the real cause, instead of guessing. If you hide that detail behind a vague message, you make the next fix much harder, for yourself and for anyone else who runs the tool.

What Write-Error, Write-Warning, and Write-Output do, in plain words: Write-Output sends normal result data, the kind of data a report is made from. Write-Warning sends a warning, a concern that does not stop the tool, such as an empty result that still lets the report finish. Write-Error sends an error message, a serious problem that should be noticed. Take care with one detail. Write-Error on its own does not stop the script by itself. If the job must stop, you must also stop it clearly, for example by returning from the function, or by using -ErrorAction Stop with Write-Error, or by using throw.

What throw does: Throw creates a terminating error on purpose, from your own code. Use it when your code detects a state that should not continue, such as an empty service name that passed an earlier check, or a report with no rows where rows are required. Throw stops the work at once, and a catch block around it can turn that stop into a clear message. Throw is not for every small concern. For a concern the tool can pass safely, use a warning instead.

Think of it like this

Think of it like this: Try, catch, and finally are like a plan for a trip. Try is the trip itself. Catch is the backup plan if the road is closed. Finally is packing up and locking the car, which you do whether the trip went well or not. A warning is like a note that the road was rough but passable. An error is like a closed road. A closed road needs a clear stop and a clear reason, not a quiet note that you drove on anyway.

How it works, step by step

How it works, step by step, in order: First, list the risky steps in your tool, such as reading a file, checking a service, or writing a report. Second, put each risky step inside a try block, and use -ErrorAction Stop where the command would otherwise report a nonterminating error. Third, add a catch block that writes a clear message, including the detail from $_.Exception.Message where it helps. Fourth, add a finally block for cleanup that must always run. Fifth, test the edge cases one by one, and fix what each test reveals. Sixth, write version notes and a sharing checklist, before you hand the tool to anyone else.

Which edge cases to test, and why each one matters: Test an empty input, because a tool that assumes at least one item will break on an empty list. Test a missing file, because a renamed or moved file is common. Test a run with no permission, because permission limits are normal in real work. Test a name that does not exist, because a typed name can be wrong. Test an output file that already exists, because overwriting a good report by accident is a real loss. Test a result with no rows, because an empty report should say it is empty, not pretend it is complete.

Let us walk through the first example, part by part: In try { Get-Content -Path .\input.txt -ErrorAction Stop } catch { Write-Error "Could not read input.txt." } finally { Write-Output "Check finished." }, try holds the file read. Get-Content reads the file. -ErrorAction Stop turns a read failure into a stopping error that catch can handle. Catch runs only if the read fails, and Write-Error reports a serious problem. Finally runs either way, so the closing message always appears. On a successful read, you see the file content plus the closing message. On a failed read, you see the error message plus the closing message, which proves finally ran even though the read failed.

Let us walk through the warning example, part by part: Write-Warning "No services matched, so the report is empty." shows a warning message, with the word WARNING at the start, so the reader cannot miss it. It reports a concern, such as an empty result, but it does not stop the tool, so the report can still finish with a clear note about why it is empty. If you change this line to Write-Error, the tone changes from a concern to a serious problem, and the reader will expect the job to have stopped or failed, so choose the stream that matches the truth of the result.

Let us walk through the Test-Path guard, part by part: Test-Path -Path .\input.txt checks if the path exists, and it returns True or False, without throwing an error for a missing file. The if statement uses -not to flip that result, so the block inside runs only when the file is missing. Inside that block, Write-Error reports the problem, and return leaves the function at once, so the tool does not try to read a file that is not there. If the file exists, the guard is skipped, and Get-Content runs as normal. A guard like this is often clearer than a try block, when the check is simple and the missing case is easy to test first.

Let us walk through the detail example, part by part: The try block reads the file with -ErrorAction Stop, as before. The catch block builds a message with two parts. The first part is your own plain words, saying what you tried to do. The second part is $($_.Exception.Message), which inserts the detail from the real error into your message. If you change that message to a generic note with no detail, the reader will know something failed but will not know why, and the fix will take longer. Keep your own words first, and the real detail second, so the message is both friendly and useful.

Let us walk through the throw example, part by part: The try block first checks if the service name is empty or only spaces, using a test for an empty value. If that test is true, throw stops the work at once with your own message, saying the service name must not be empty. Because throw creates a terminating error, the catch block runs, and Write-Error reports the problem in plain words. If the name is not empty, throw never runs, and Get-Service runs as normal. Throw is the right choice here, because a report for an empty name would be meaningless, so the tool should stop, not warn and continue.

When to use it

When to use it, and when not to: Use try and catch for steps that can fail for reasons outside your control, such as files, services, and permissions. Use Write-Error for a failure that should be noticed as serious, and pair it with a clear stop when the job must not continue. Use Write-Warning for a concern the tool can safely pass. Do not hide every error with a vague message. Do not use -ErrorAction SilentlyContinue to hide a real failure, because a hidden failure will return later as a wrong report. Do not use a warning for a failure that makes the result wrong.

How to finish a tool well: A finished tool has version notes and a sharing checklist. Version notes say which version this is, what changed from the last version, and what still needs work. A sharing checklist asks, in order: Does it run in a fresh session? Does it handle an empty input, a missing file, and a run with no permission? Does it write a log or a report you have read? Did you test it on small, safe data first, on your own computer? Did you back up anything it might overwrite? If any answer is no, fix that item before you share the tool, and before you schedule it.

Safety, one more time, because it matters most at the finish line: Test on small, safe data first. Back up before any change. Read the report before you share it. Never schedule an untested tool that changes or deletes data. A tool that is shared or scheduled is no longer only your tool. It becomes a promise to every person who runs it, and to every run that happens while you are not watching.

Worked examples

Read each example in order. Each one explains its parts, then shows what to look for in the output.

Syntax

Syntax
try { <commands> } catch { <handle error> } finally { <cleanup> }

Example 1

Get-Content reads a file, and -ErrorAction Stop makes a failure stop so catch can handle it. The catch block reports the problem with Write-Error. The finally block runs either way, so the closing message always appears, on success and on failure.

Example 1
try {
  Get-Content -Path .\input.txt -ErrorAction Stop
} catch {
  Write-Error "Could not read input.txt."
} finally {
  Write-Output "Check finished."
}

Illustrative output: Check finished.

Example 2

Write-Warning shows a warning message. It reports a concern, such as an empty result, but it does not stop the tool, so the report can still finish with a clear note about why it is empty. Look for the word WARNING at the start of the line.

Example 2
Write-Warning "No services matched, so the report is empty."

Illustrative output: WARNING: No services matched, so the report is empty.

Example 3

Test-Path checks if the path exists and returns True or False, without throwing an error for a missing file. If the file is missing, the if block reports the problem and return leaves the function at once. If the file exists, the guard is skipped and Get-Content reads the file. This guard is clearer than a try block when the missing case is easy to check first.

Example 3
if (-not (Test-Path -Path .\input.txt)) {
  Write-Error "Input file not found: input.txt."
  return
}
Get-Content -Path .\input.txt

Illustrative output: Input file not found: input.txt.

Example 4

This catch block keeps your own plain words first, then adds the real error detail with $($_.Exception.Message). The detail tells the reader why the read failed, so the fix is faster. If you remove the detail part, the reader will know something failed but will not know why.

Example 4
try {
  Get-Content -Path .\input.txt -ErrorAction Stop
} catch {
  Write-Error "Could not read input.txt. Detail: $($_.Exception.Message)"
}

Illustrative output: Could not read input.txt. Detail: Cannot find path because it does not exist.

Example 5

The if test checks for an empty name or a name made only of spaces. If the test is true, throw stops the work at once with your own message. Catch then reports that message as an error. If the name is not empty, throw never runs and Get-Service runs as normal. Use throw when a bad state must stop the job, not when a warning would do.

Example 5
try {
  if ([string]::IsNullOrWhiteSpace($Name)) {
    throw "Service name must not be empty."
  }
  Get-Service -Name $Name
} catch {
  Write-Error "Service check failed: $($_.Exception.Message)"
}

Illustrative output: Service check failed: Service name must not be empty.

Nothing on this page executes PowerShell code. The outputs above are illustrative only.

Common mistakes and troubleshooting

Read these before you try the examples, so you can spot the same problems in your own work.

  • Catching an error and hiding it with no message, so nobody knows the report is incomplete.
  • Using Write-Warning for a failure that makes the result wrong, instead of Write-Error.
  • Testing only the happy path, and never trying an empty input, a missing file, or a run with no permission.
  • Forgetting -ErrorAction Stop, so a nonterminating error never reaches catch, and the tool carries on as if nothing went wrong.
  • Putting the main result in finally, so it appears even when the job failed, or putting cleanup only in catch, so cleanup is skipped on success.
  • Using Write-Error and assuming the script stopped, then letting later steps run with bad or missing data.
  • Catching every error with one vague message, and throwing away the detail from $_.Exception.Message that would have shown the real cause.
  • Sharing or scheduling a tool without version notes, a sharing checklist, a test on small safe data, and a back up of anything it might overwrite.

Knowledge check

Knowledge check

What does the finally block do?

Pick one answer. Feedback appears right away, and you can try again.

Remember this and next step

Remember this: Try holds risky work, catch handles failure with a clear message that keeps the real detail, finally cleans up either way, -ErrorAction Stop turns a nonterminating error into one catch can handle, Write-Error signals a serious problem, Write-Warning notes a concern the tool can pass, throw stops the work when your own code finds a state that must not continue, and a finished tool is tested on edge cases, versioned with notes, and checked against a sharing checklist before anyone else runs it.

Next step: you have finished this chapter. Return to all chapters.