Catch exception

12/10/2012 18:28

#save previous setting

$defaultErrorAction=$ErrorActionPreference

#Force program to catch exception in case of error
$ErrorActionPreference="Stop"
try
{

#use some method with specified exception
    $item=$WorkItemStore.GetWorkItem(20156)
}
catch [Exception]
{

#compare exception type name
   if($error[0].GetType().Name -match "MethodInvocationException" -or ($error[0].GetType().Name -match "ErrorRecord"))
   {
    write-host "I got it"
   }
   else
   {
   write-host "Unknown Error."
   }
  
}
finally

#restore original setting for catching errors
{$ErrorActionPreference=$defaultErrorAction}