O'Reilly logo

Windows PowerShell™ 3.0 Step by Step by Ed Wilson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using Try...Catch...Finally

When using a Try...Catch...Finally block, the command you wish to execute is placed in the Try block. If an error occurs when the command executes, the error will be written to the $error variable, and script execution moves to the Catch block. The TestTryCatchFinally.ps1 script, which follows, uses the Try command to attempt to create an object. A string states that the script is attempting to create a new object. The object to create is stored in the $obj1 variable. The New-Object cmdlet creates the object. Once the object has been created and stored in the $a variable, the members of the object are displayed via the Get-Member cmdlet. This code illustrates the technique:

Try { "Attempting to create new object $obj1" ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required