WPS differentiates between errors where the termination of an execution is mandatory (terminating error) and errors where the execution may be continued with the next command (nonterminating error). Terminating errors can be caught with Trapcommands. Nonterminating errors, on the other hand, can be changed into terminating ones.
Trapcatches occurring terminating errors and executes the indicated code (see Table 7.1). In the error handling code, the variable $_contains information about the error in the form of an instance of the .NET class System.Management.Automation.ErrorRecord. The subobject
$_.Exception is the actual error in the form of an instance of an error class that inherits from System.Exception. Via $_.Exception.
GetType().FullName, you get the error type. Via $_.Exception.
Message, you display the error text.
With the statements Break or Continue, the error handler is told whether the script will be continued after the error. The default procedure isContinue. With Exit, you can cause a definite immediate ending of the whole script.
Example
With Listing 7.3, you can test WPS error behavior and experiment with the different reaction options. The error is resolved by the call Copy-Item with a wrong path (a nonterminating error) and Get-Dir. (This com-mandlet does not exist; it’s a terminating error.)
Listing 7.3 Script for Testing the Trap Statement
# Example for the testing of error trapping
trap {
Write-Host ("### trapped ERROR: " +
$_.Exception.Message)
#Write-Error ("Fehler: " + $_.Exception.Message)
#continue
#break
#exit
#throw "test"
}
"Example for the testing of error trapping "
"At first, everything works fine..."
copy g:\Documents\Suppliers c:\temo\Documents
"Then it doesn’t work so fine anymore (false path)"
copy g:\Documents\Suppliers k:\Documents\Suppliers
"And then an unknown commandlet follows"
Get-Dir k:\Documents\Suppliers
"End of Script"
Errors and Error Treatment 123
7.POWERSHELLSCRIPTS
Table 7.1 Reaction of WPS to Errors When Trap Is Used
Trap Reaction
Not existing WPS shows error reports for Copy-Item (“drive does not exist”) and Get-Dir(“not recognized as a cmdlet, function, program, or script file”) and continues the execution until the end of the script.
Existing, only with In addition to the WPS error report, the Trap block reports Write-Host its own error text.
Existing, with Just the error text from the Trapblock displays.
continue
Errors and Error Treatment 125
7.POWERSHELLSCRIPTS
Existing, with break The terminating error results first in its own error text, followed by a WPS error text display. After that, the script is terminated (i.e., the output “End of Scripts” does not display).
Existing, with exit The terminating error results first in its own error text. Then the execution stops immediately.
Individual Reactions to Errors
The options vary even more because each single commandlet can decide via the parameter –ErrorAction(or–ea) how errors will be handled:
Trap Reaction
■ Stop The error is displayed, and the execution is terminated (all nonterminating errors thus become terminating errors).
■ Continue The error is displayed, and the execution is continued.
■ SilentlyContinue The error is not displayed, and the execution is continued.
■ Inquire Users are asked whether they want to continue the exe-cution despite the error.
All the possible combinations of –ErrorAction andTrapare beyond the scope of this book. Therefore, this text contains just sample cases (see Table 7.2).
NOTE The application of –ErrorActionhas an effect only on existing com-mandlets. The nonexisting commandlet Get-Dir, which is used in the example, would not be able to react.
Table 7.2 WPS Reaction to Errors When Trap and –ErrorAction Are Used Trap ErrorAction Reaction
Not existing -ErrorAction An error report for the path error does silentlycontinue not appear any longer with Copy-Item.
The problem will be further reported withGet-Dir.
Existing, with -ErrorAction A standard WPS error report doesn’t continue silentlycontinue appear at all, but only the user-defined
report from the Trap block for the nonexisting commandlet.
Not existing -ErrorAction stop The execution is terminated with a WPS error report, directly after the first nonexecutable Copy command.
Errors and Error Treatment 127
7.POWERSHELLSCRIPTS
Existing, with -ErrorAction stop For both errors, just the error text
continue from the Trap block displays.
Further Options
WPS offers us even more with regard to error treatment:
■ Via the global integrated variable $ErrorActionPreference, you can set the standard reaction –ErrorAction for all commandlets.
This is in the standard setting Continue.
Trap ErrorAction Reaction
■ $Error contains the complete history of errors in the form of objects that belong to error classes (for example, System.
Management.Automation.CommandNotFoundException).
■ Trapblocks can be limited to certain error groups by indicating an error type in square brackets (error class). Therefore, one script can contain several Trapblocks.
■ With Throw, you can create any error of your own within or outside of Trap blocks. Throw creates a terminating error of the class System.Management.Automation.RuntimeException. You can also name another error class in square brackets. The class has to be a class that derives from System.Exception.
throw "error text"
throw [System.ApplicationException] "error text"
Summary
WPS scripts are text files with the extension .ps1, and you can start a script in several different ways. And although the default security restrictions in WPS prevent all scripts from executing, you can use the commandlet Set-Executionpolicyto lower the security settings on the execution policy.
Instead of allowing all scripts to run, you should use WPS modes that require digitally signed scripts.
The second big topic in this chapter was error treatment, which is important in scripts. This chapter examined the differences between ter-minating errors and nonterter-minating errors. The chapter also provided numerous examples that showed how to catch an error with the Trap state-ment and how to configure the error behavior (reaction) of commandlets with the parameter ErrorAction.
129 C H A P T E R 8