Chapter 30. Error handling techniques

 

This chapter covers

  • Error handling parameters and variables
  • Trap
  • Try...Catch...Finally

You’ll inevitably write a script that contains a command that fails. Failure is often something you can anticipate: A computer isn’t online or reachable, a file can’t be found, access is denied, and other similar conditions are all ones that you expect from time to time. PowerShell enables you to catch those errors and handle them in your own way. For example, you might want to log a failed computer name to a file for retrying, or you might want to write an entry to the Windows event log when access is denied. Error handling is the process of identifying these conditions, catching the error, and doing something about it while continuing your processes on other machines.

The point of this chapter isn’t just to teach you how to catch errors but rather how to handle errors gracefully. A simple script that fails when it encounters an error is handling it, but not very well if it fails on the first computer of 30, which means you have to restart the script. This is especially bad news if the script ran as an overnight activity. Proper application of error handling techniques enables you to be more productive. Which do you want your script to report: “I did 299 out of 300 machines and failed on this one” or “It failed”?

30.1. About errors and exceptions

 
 

30.2. Using $ErrorActionPreference and –ErrorAction

 
 
 

30.3. Using –ErrorVariable

 

30.4. Using $Error

 
 
 
 

30.5. Trap constructs

 
 
 

30.6. Try...Catch...Finally constructs

 
 
 

30.7. Summary

 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest