Lessons In PowerShell - Exception Handling

   Submit to Reddit      
  

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.

throw "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.

Trap [ExceptionType] 
{
    if (...) 
    { 
        continue
    } else (...)
    { 
        break
    }

    # Doing nothing will do what is specified in the $ErrorActionPreference setting
}

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.

&{
     &{   # Try
          # Do your processing here
     } 
     trap # Catch
     {
         Write-Host "TRAPPED: " + $_.Exception.GetType().FullName
         Write-Host "TRAPPED: " + $_.Exception.Message
         continue   # So that the "Finally" stuff gets executed
     }
} #Finally
# Put your finally code here

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

    try {
        ...
    } catch {
        ...
    }


comments powered by Disqus