PowerShell Try Catch Finally

When you need to handle the terminating errors within the script blocks, use a Try, Catch, and finally blocks in a PowerShell.

The terminating errors are those errors which stop the statement from running. When PowerShell does not handle the terminating errors in some way, then it also stops running a script or function using the current pipeline. In other languages, such as C, these errors are referred to as exceptions.

Try {……..}

Try block is the part of a script where you want PowerShell to monitor for errors. When an error occurs in this block, it is first stored in the automatic variable $Error. After that, PowerShell searches for the Catch block to handle it.

If the Try block does not have a matching Catch block, then the PowerShell searches in the parent scopes for an appropriate Trap or Catch block.

Syntax of Try Block

The following box shows the syntax of the try block:

try   

{  

          Statement-1  

          Statement-2  

          Statement-N  

}

      

A Try statement must have at least one catch or one finally block. In the above syntax, the Try keyword is followed by single or multiple statements in the braces.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *