Using trap

trap is declared in a similar manner to the catch block:

trap { <script> } 
trap [ExceptionType] { <script> } 
trap [ExceptionType1], [ExceptionType2] { <script> } 

A script may contain more than one trap statement, for example:

trap [InvalidOperationException] { 
    Write-Host 'An invalid operation' 
} 
trap { 
    Write-Host 'Catch all other exceptions' 
} 

The ordering of the preceding trap statements does not matter; the most specific statement is used to handle a given error.

When using a script, function, or script block, the trap statement can appear anywhere. trap does not have to appear before the code it acts against. For example, trap is implemented in the script block that is called as follows:

& { 
    Write-Host 'Statement1' 
    throw 'Statement2' 
    Write-Host 'Statement3' 
 
    trap { Write-Host 'An error occurred' } 
} 

The error raised by throw causes the trap statement to execute and execution stops; Statement3 is never written.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.51.157