The following useful information is primarily taken from the Windows PowerShell Language Quick Reference (QuadFold.rtf) documentation.

Throw

The keyword “Throw” allows an exception to be thrown. The argument for the Throw keyword can be a string, exception or ErrorRecord.

1throw "Some description about the exception"

Traps

A trap is a mechanism to catch an exception, although it behave more like the Visual Basic 6 On Error functionality. The continue keyword will continue execution at the script statement after the one that caused the trap. $? is updated but no error record is generated. The break keyword will rethrow the exception.

 1Trap [ExceptionType] 
 2{
 3    if (...) 
 4    { 
 5        continue
 6    } else (...)
 7    { 
 8        break
 9    }
10
11    # Doing nothing will do what is specified in the $ErrorActionPreference setting
12}

Try / Catch / Finally

There is no native support in PowerShell Version 1 for the typical Try / Catch / Finally syntax found in other languages. However with the use of the & invoke operator, the Try / Catch / Finally syntax can be mimicked.

 1&{
 2     &{   # Try
 3          # Do your processing here
 4     } 
 5     trap # Catch
 6     {
 7         Write-Host "TRAPPED: " + $_.Exception.GetType().FullName
 8         Write-Host "TRAPPED: " + $_.Exception.Message
 9         continue   # So that the "Finally" stuff gets executed
10     }
11} #Finally
12# Put your finally code here

However, from PowerShell Version 2, you can use the familiar try / catch syntax.

1    try {
2        ...
3    } catch {
4        ...
5    }
Please leave below any comments, feedback or suggestions, or alternatively contact me on a social network.

comments powered by Disqus