mariu5
mariu5

Reputation: 455

Catching unexpected errors in PowerShell

So I've been doing my error handling in Powershell with Try/Catch so far and whenever an error occurs, it gets written to a log file.

Now how could I handle unexpected errors? Should I just put the whole script code in a Try/Catch block or is there a better method to do this?

Thanks for any help.

Upvotes: 2

Views: 1721

Answers (2)

Johan de Haan
Johan de Haan

Reputation: 1018

You are right. When you use the default try/catch(/finally) statements all exception will be trapped in the catch block.

try { 

  Do-Someting

} catch {

  Write-Host "Caught the following error: $($_.Exception.Message)"

} finally {

  Write-Host "Finally, we made it!"

}

When you specifically add an exception to catch, you can create specific actions for that exception:

try{

  Do-Something

} catch [System.Management.Automation.ItemNotFoundException]{

  # catching specific exceptions allows you to have
  # custom actions for different types of errors
  Write-Host "Caught an ItemNotFoundException: $($_.Exception.Message)" -ForegroundColor Red

} catch {

  Write-Host "General exception: $($_.Exception.Message)"

}

Upvotes: 1

Martin Brandl
Martin Brandl

Reputation: 59021

Yes, there is. You can define a Trap at the top of your script and Log the last error:

trap
{
    Write-host $Error[0] 
}

Upvotes: 2

Related Questions