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 doesn't matter; the statement with the most specific error type is used to handle a given error.

PowerShell, as a script-based language normally executes statements in the order written. However, when using a script, function, or script block, the trap statement can appear anywhere; trap doesn't have to appear before the code it acts against. For example, the trap implemented at the bottom of the script block will used when the preceding code raises an error:

& { 
    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 then 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.128.226.255